Calling Constructor in Spring
In the given example you will be learning about a constructor and how to call a constructor in the Spring. Declaring constructor injection in the Spring framework is generally done in the bean section of the configuration file that is the context.xml file.
Steps to declare Constructor Injection:
1)Set the constructor declaration
2)Pass the value to the constructor.
This tutorial describes the way of defining constructor in the xml document and retrieving
the values defined in the constructor using java file.
<constructor-arg>
<util:map> <entry key="CompanyName" value="Roseindia.net"/> <entry key="Address" value="Rohini"/> </util:map> </constructor-arg> |
<constructor-arg>:-This is the way to
declare the constructor injection consisting of arguments. The use of this
injection is to tell the container that the application wants to use the Constructor Injection.
<entry key="CompanyName" value="Roseindia.net"/>:-Passing
the value to the constructor is usually done through the <value>element. Here
we have pass "Roseindia.net " as the company name.
context.xml
<?xml version="1.0" encoding="UTF-8"?>
|
Here is the file named Main.java through which we are
retrieving the properties of the bean which we have defined in the above file
i.e. context.xml
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml")):-Here
we are creating an instance of the XmlBeanFactory which is used to read
bean definition from an XML document
new ClassPathResource("context.xml"):-Creates a new
ClassPathResource for ClassLoader .Here the context.xml is the file which is to
be loaded.
Main.java
import java.util.Map;
|
Output of the program
Nov 26, 2008 12:48:55 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] Name of the company is: Roseindia.net Address of the company is: Rohini BUILD SUCCESSFUL (total time: 1 second) |