@ConstructorProperties is used in constructor based dependency injection.It is mainly used when we need the constructor arguments passed in the application context(metadata to the spring container) should be resolved by the constructor parameter name in the bean object to be created.By annotating @ConstructorProperties in the constructor of the bean class,it will make the constructor parameter names available to the spring container at runtime.Below sample will show how this annotation can be used:
- Person - Bean class in which container will inject the dependencies through constructor arguments
- personcontext.xml - metadata configuration details for the spring container
- PersonDemo - Main class which will load the spring container and get the person bean from the container.
Person.java
package test;
import java.beans.ConstructorProperties;
public class Person {
private String name;
private int age;
@ConstructorProperties({"pername", "perage"})
public Person(String pername, int perage) {
super();
this.name = pername;
this.age = perage;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
|
Since we have annotated the constructor parameters with @ConstructorProperties,the constructor parameter names(pername and perage) will be available to Spring container at runtime.
personcontext.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="person" class="test.Person">
<constructor-arg name="pername" value="Ram"/>
<constructor-arg name="perage" value="21"/>
</bean>
</beans>
|
As we can see in the application context file,we use the constructor parameter names to inject the dependencies.
PersonDemo.java
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PersonDemo {
public static void main(String[] args) {
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]
{"personcontext.xml"});
Person person= bf.getBean("person",Person.class);
System.out.println(person);
}
}
|
OUTPUT
Person [name=Ram, age=21]
|