Home Tutorial Spring Spring3 Ioc Spring Constructor Injection


Share on Google+Share on Google+
Spring Constructor Injection
Posted on: August 2, 2010 at 12:00 AM
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;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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="http://www.springframework.org/schema/beans"
  <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


Related Tags for Spring Constructor Injection:

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.

Posted on: August 2, 2010

Recommend the tutorial

Advertisements Advertisements