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
Advertisement
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.

ConstructorInjection.java

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;
  }
}

ConstructorInjectionTest.java

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(
        "context.xml");
    ConstructorInjection bean = (ConstructorInjectionbeanfactory
        .getBean("basic");
    System.out.println(bean.getMessage());
  }
}

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 
xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
  <bean id="basic" class="net.roseindia.ConstructorInjection">
    <constructor-arg value="Hello Spring" />
  </bean>
</beans>

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

Hello Spring 

Download this example code

Advertisement

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
 

 

 

DMCA.com