Instead of using the setter methods to inject values to attributes,
the constructor of a class can be used to inject the values from outside
the class. This work again, is done through the spring metadata file ,
as is in the case of setter injection.
** UPDATE: Spring Complete tutorial now available here.
File : SimpleConstructorInjection
The value for the attribute of the POJO is provided as<constructor-arg value=” ” /> thereby setting the values of these attributes through the constructor.
File : Beans.xml
File : MainClass.java
** UPDATE: Spring Complete tutorial now available here.
1. Create the POJO class into which values are to be injected using setter injection
File : SimpleConstructorInjection
package com.simpleCodeStuffs; public class SimpleConstructorInjection { public SimpleConstructorInjection(String message){ this.message=message; } private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } }
Note : Unlike setter injection, a constructor has to be explicitly defined for the POJO in case of constructor injection. This is because, usually a default(no parameter) constructor is taken up. But since we will be passing a value to the constructor of this POJO to instantiate it, we require a constructor whose parameters match the set of values passed from the xml.
2 Define the metadata
The value for the attribute of the POJO is provided as<constructor-arg value=” ” /> thereby setting the values of these attributes through the constructor.
File : Beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="simpleConstructorInjection" class=
"com.simpleCodeStuffs.SimpleConstructorInjection"> <constructor-arg value="SimpleCodeStuffs--Simple Constructor Injection"/> </bean> </beans>
The values are injected into the POJO through the constructor of these classes
3. Write the main class to place a call to this POJO
File : MainClass.java
package com.simpleCodeStuffs; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainClass { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); SimpleConstructorInjection obj = (SimpleConstructorInjection)
context.getBean("simpleConstructorInjection"); obj.getMessage(); } }