Share on Google+Share on Google+

Spring Constructor Injection

In this example you will see Basic Constructor Injection

Basic Constructor Injection

In this example you will see how the Spring beans XML file used to configure your bean to initialize with an argument for the constructor, and then assign the argument. This all process can also be said as injecting the argument into your bean and widely known as constructor injection.

package net.roseindia;

public class ConstructorInjection {
  private String message = null;

  public ConstructorInjection(String message) {
    this.message = message;

  public String getMessage() {
    return message;

  public void setMessage(String message) {
    this.message = message;

package net.roseindia;

import org.springframework.beans.factory.BeanFactory;

public class ConstructorInjectionTest {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
    ConstructorInjection bean = (ConstructorInjectionbeanfactory


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
  <bean id="basic" class="net.roseindia.ConstructorInjection">
    <constructor-arg value="Hello Spring" />

When you run this application it display output as shown below:

Hello Spring 

Download this example code


Posted on: August 2, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null