
Dependency Injecting with constructors
Every instance in Java needs to call the constructor once in the lifetime. In Spring constructors can also be used to inject the various properties using the metadata. There are various ways we can supply the properties to the constructor of the bean.
- Writing in sequence all the properties using <constructor-arg value/value-ref="XXX" /> tag.
- Using the indexes in the <constructor-arg [index="0"] value/value-ref="XXX" /> tag.
- Using the datatype to map the arguments with the parameters example <constructor-arg [type="datatype"] value/value-ref="XXX" />
The coming example will use the all three types in the same wiring.
Example :-
package com.visualbuilder.beans; public class ConstructorInjectionBean { |
<bean id="constructorInjection" class="com.visualbuilder.beans.ConstructorInjectionBean"> |
ConstructorInjectionExample.java
package com.visualbuilder.example; import org.springframework.context.ApplicationContext; import com.visualbuilder.beans.ConstructorInjectionBean; public class ConstructorInjectionExample { |
Output:-
Jun 1, 2008 7:07:47 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc: display name [org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc]; startup date [Sun Jun 01 19:07:47 IST 2008]; root of context hierarchy
Jun 1, 2008 7:07:47 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/visualbuilder/xml/spring-beans.xml]
Jun 1, 2008 7:07:47 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@c4bcdc]: org.springframework.beans.factory.support.DefaultListableBeanFactory@15e83f9
Bean is created
Assigned Name is John Smith
Assigned Age is 25
Assigned Sex is M
Jun 1, 2008 7:07:47 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@15e83f9: defining beans [test,collectionExample,typeCollectionExample,constructorInjection,setterInjection]; root of factory hierarchy
Java Discussion
- - Difference between BMT an
- - Replace getParameterValue
- - Interviewing Next week -
- - Sudoku solver
- - Setting tab order in swin



