UNIT I: Spring 5 Basics : Why Spring, What is Spring Framework, Spring Framework - Modules,
Configuring IoC container using Java-based configuration, Introduction To Dependency Injection,
Constructor Injection, Setter Injection, What is Auto Scanning
Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of frameworks because it
provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The
framework, in broader sense, can be defined as a structure where we find solution of the various
technical problems.
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB
MVC etc. We will learn these modules in next page. Let's understand the IOC and Dependency
Injection first.
Advantages of Spring Framework
There are many advantages of Spring Framework. They are as follows:
1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no
need to write too much code. It hides the basic steps of these technologies.
Let's take the example of JdbcTemplate, you don't need to write the code for exception
handling, creating connection, creating statement, committing transaction, closing connection
etc. You need to write the code of executing query only. Thus, it save a lot of JDBC code.
2) Loose Coupling
The Spring applications are loosely coupled because of dependency injection.
3) Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application
require server to run the application but Spring framework doesn't require server.
4) Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework
doesn't force the programmer to inherit any class or implement any interface. That is why it is
said non-invasive.
5) Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks
makes the easy development of JavaEE application.
6) Powerful abstraction
It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
7) Declarative support
It provides declarative support for caching, validation, transactions and formatting.
Modules
The Spring Framework contains a lot of features, which are well-organized in about twenty
modules. These modules can be grouped together based on their primary features into Core
Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation
and Test. These groups are shown in the diagram below.
Overview of the Spring Framework
1.2.1 Core Container
The Core Container consists of the Core, Beans, Context and Expression modules.
The Core and Beans modules provide the most fundamental parts of the framework and
provides the IoC and Dependency Injection features. The basic concept here is
the BeanFactory which provides a sophisticated implementation of the factory pattern. It
removes the need for programmatic singletons and allows you to decouple the configuration
and specification of dependencies from your actual program logic.
The Context module build on the solid base provided by the Core and Beans modules: it
provides a way to access objects in a framework-style manner in a fashion somewhat
reminiscent of a JNDI-registry. The Context module inherits its features from the Beans module
and adds support for internationalization (I18N) (using for example resource bundles), event-
propagation, resource-loading, and the transparent creation of contexts by, for example, a
servlet container. The Context module also contains support for some Java EE features like EJB,
JMX and basic remoting support. The ApplicationContext interface is the focal point of the
Context module that provides these features.
The Expression Language module provides a powerful expression language for querying and
manipulating an object graph at runtime. It can be seen as an extension of the unified
expression language (unified EL) as specified in the JSP 2.1 specification. The language supports
setting and getting of property values, property assignment, method invocation, accessing the
context of arrays, collections and indexers, logical and arithmetic operators, named variables,
and retrieval of objects by name from Spring's IoC container. It also supports list projection and
selection, as well as common list aggregators.
1.2.2 Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction
modules.
The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC
coding and parsing of database-vendor specific error codes.
The ORM module provides integration layers for popular object-relational mapping APIs,
including JPA, JDO, Hibernate, and iBatis. Using the ORM package you can use all those O/R-
mappers in combination with all the other features Spring offers, such as the simple declarative
transaction management feature mentioned previously.
The OXM module provides an abstraction layer for using a number of Object/XML mapping
implementations. Supported technologies include JAXB, Castor, XMLBeans, JiBX and XStream.
The JMS module provides Spring's support for the Java Messaging Service. It contains features
for both producing and consuming messages.
The Transaction module provides a way to do programmatic as well as declarative transaction
management, not only for classes implementing special interfaces, but for all your POJOs (plain
old Java objects).
1.2.3 Web
The Web layer consists of the Web, Web-Servlet and Web-Portlet modules.
Spring's Web module provides basic web-oriented integration features, such as multipart file-
upload functionality, the initialization of the IoC container using servlet listeners and a web-
oriented application context. It also contains the web related parts of Spring's remoting support.
The Web-Servlet module provides Spring's Model-View-Controller (MVC) implementation for
web-applications. Spring's MVC framework is not just any old implementation; it provides
a clean separation between domain model code and web forms, and allows you to use all the
other features of the Spring Framework.
The Web-Portlet module provides the MVC implementation to be used in a portlet environment
and mirrors what is provided in the Web-Servlet module.
1.2.4 AOP and Instrumentation
Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming
implementation allowing you to define, for example, method-interceptors and pointcuts to
cleanly decouple code implementing functionality that should logically speaking be separated.
Using source-level metadata functionality you can also incorporate all kinds of behavioral
information into your code, in a manner similar to that of .NET attributes.
There is also a separate Aspects module that provides integration with AspectJ.
The Instrumentation module provides class instrumentation support and classloader
implementations to be used in certain application servers.
1.2.5 Test
The Test module contains the Test Framework that supports testing Spring components using
JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of
those contexts. It also contains a number of Mock objects that are usful in many testing
scenarios to test your code in isolation.
Spring IOC Container Java Config Example
Now in this article, we will discuss a simple example to demonstrate Spring IOC Container with
Java-based configuration metadata?
The Spring IOC container is responsible for instantiating, configuring, and assembling the Spring
beans. The container gets its instructions on what objects to instantiate, configure, and assemble
by reading configuration metadata. The configuration metadata is represented in XML, Java
annotations, or Java code. It lets you express the objects that compose your application and the
rich interdependencies between those objects.
Three ways we can supply Configuration Metadata to the Spring IoC container:
1. XML-based configuration
2. Annotation-based configuration
3. Java-based configuration
Spring IOC Container Java Config Example
In this example, we will supply Java-based configuration metadata to the Spring IoC container.
Development Steps
Follow these five steps to develop a spring application:
1. Create a simple Maven Project
2. Project Structure
3. Add Maven Dependencies
4. Configure HelloWorld Spring Beans
5. Create a Spring Container
6. Retrieve Beans from Spring Container
Tools and technologies used
Spring Framework - 6.0.5
JDK - 17 or later
Maven - 3.2+
IDE - Eclipse Mars/STS
1. Create a simple Maven Project
Create a simple maven project using your favorite IDE and refer below diagram for the
packaging structure. If you are new to maven then read this article How to Create a Simple
Maven Project.
2. Project Structure
The below diagram shows a project structure for your reference -
3. Add Maven Dependencies
Add the following content to the [Link] file:
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>spring-ioc-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<[Link]>17</[Link]>
<[Link]>17</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
</project>
4. Configure HelloWorld Spring Beans
What is a Spring Bean?
This is a very simple question that is often overcomplicated. Usually, Spring beans are Java
objects that are managed by the Spring container.
Let's create a HelloWorld Java class with the following content:
package [Link];
public class HelloWorld {
private String message;
public void setMessage(String message) {
[Link] = message;
}
public void getMessage() {
[Link]("My Message : " + message);
}
}
Next, Let's configure the HelloWorld class as Spring bean using Java-based configuration:
package [Link];
import [Link];
import [Link];
@Configuration
public class AppConfig {
@Bean
public HelloWorld helloWorld() {
HelloWorld helloWorld = new HelloWorld();
[Link]("Hello World!");
return helloWorld;
}
}
Spring @Configuration annotation is part of the spring core framework. Spring Configuration
annotation indicates that the class has @Bean definition methods. So Spring container can
process the class and generate Spring Beans to be used in the application.
5. Create a Spring Container
Let's create a Spring container object
using AnnotationConfigApplicationContext implementation class of
the ApplicationContext interface:
package [Link];
import [Link];
import [Link];
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
[Link]();
}
}
6. Retrieve Beans from Spring Container
ApplicationContext interface provides the getBean() method to retrieve the bean from the
Spring container.
package [Link];
import [Link];
public class Application {
public static void main(String[] args) {
// ApplicationContext context = new
ClassPathXmlApplicationContext("[Link]");
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
HelloWorld obj = (HelloWorld) [Link]("helloWorld");
[Link]();
[Link]();
}
}
Output
My Message : Hello World!
GitHub
The source code of this example is available on my GitHub repository.
Dependency Injection in Spring
Dependency Injection (DI) is a design pattern that removes the dependency from the
programming code so that it can be easy to manage and test the application. Dependency
Injection makes our programming code loosely coupled.
In such case we write the code as:
1. class Employee{
2. Address address;
3.
4. Employee(Address address){
5. [Link]=address;
6. }
7. public void setAddress(Address address){
8. [Link]=address;
9. }
10.
11. }
In such case, instance of Address class is provided by external souce such as XML file
either by constructor or setter method.
Two ways to perform Dependency Injection in Spring framework
Spring framework provides two ways to inject dependency
o By Constructor
o By Setter method
Dependency Injection by Constructor Example
We can inject the dependency by constructor. The <constructor-arg> subelement
of <bean> is used for constructor injection. Here we are going to inject
1. primitive and String-based values
2. Dependent object (contained object)
3. Collection values etc.
Injecting primitive and string-based values
Let's see the simple example to inject primitive and string-based values. We have created three
files here:
o [Link]
o [Link]
o [Link]
[Link]
It is a simple class containing two fields id and name. There are four constructors and one
method in this class.
1. package [Link];
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. public Employee() {[Link]("def cons");}
8.
9. public Employee(int id) {[Link] = id;}
10.
11. public Employee(String name) { [Link] = name;}
12.
13. public Employee(int id, String name) {
14. [Link] = id;
15. [Link] = name;
16. }
17.
18. void show(){
19. [Link](id+" "+name);
20. }
21.
22. }
[Link]
We are providing the information into the bean by this file. The constructor-arg element invokes
the constructor. In such case, parameterized constructor of int type will be invoked. The value
attribute of constructor-arg element will assign the specified value. The type attribute specifies
that int parameter constructor will be invoked.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="e" class="[Link]">
10. <constructor-arg value="10" type="int"></constructor-arg>
11. </bean>
12.
13. </beans>
[Link]
This class gets the bean from the [Link] file and calls the show method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link].*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)[Link]("e");
14. [Link]();
15.
16. }
17. }
Output:10 null
download this example
Injecting string-based values
If you don't specify the type attribute in the constructor-arg element, by default string type
constructor will be invoked.
1. ....
2. <bean id="e" class="[Link]">
3. <constructor-arg value="10"></constructor-arg>
4. </bean>
5. ....
If you change the bean element as given above, string parameter constructor will be invoked
and the output will be 0 10.
Output:0 10
You may also pass the string literal as following:
1. ....
2. <bean id="e" class="[Link]">
3. <constructor-arg value="Sonoo"></constructor-arg>
4. </bean>
5. ....
Output:0 Sonoo
You may pass integer literal and string both as following
1. ....
2. <bean id="e" class="[Link]">
3. <constructor-arg value="10" type="int" ></constructor-arg>
4. <constructor-arg value="Sonoo"></constructor-arg>
5. </bean>
6. ....
Dependency Injection by setter method
We can inject the dependency by setter method also. The <property> subelement
of <bean> is used for setter injection. Here we are going to inject
1. primitive and String-based values
2. Dependent object (contained object)
3. Collection values etc.
Injecting primitive and string-based values by setter method
Let's see the simple example to inject primitive and string-based values by setter method. We
have created three files here:
o [Link]
o [Link]
o [Link]
[Link]
It is a simple class containing three fields id, name and city with its setters and getters and a
method to display these informations.
1. package [Link];
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private String city;
7.
8. public int getId() {
9. return id;
10. }
11. public void setId(int id) {
12. [Link] = id;
13. }
14. public String getName() {
15. return name;
16. }
17. public void setName(String name) {
18. [Link] = name;
19. }
20.
21. public String getCity() {
22. return city;
23. }
24. public void setCity(String city) {
25. [Link] = city;
26. }
27. void display(){
28. [Link](id+" "+name+" "+city);
29. }
30.
31. }
[Link]
We are providing the information into the bean by this file. The property element invokes the
setter method. The value subelement of property will assign the specified value.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="obj" class="[Link]">
10. <property name="id">
11. <value>20</value>
12. </property>
13. <property name="name">
14. <value>Arun</value>
15. </property>
16. <property name="city">
17. <value>ghaziabad</value>
18. </property>
19.
20. </bean>
21.
22. </beans>
[Link]
This class gets the bean from the [Link] file and calls the display method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link].*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee e=(Employee)[Link]("obj");
14. [Link]();
15.
16. }
17. }
Dependency Injection by Constructor Example
We can inject the dependency by constructor. The <constructor-arg> subelement
of <bean> is used for constructor injection. Here we are going to inject
1. primitive and String-based values
2. Dependent object (contained object)
3. Collection values etc.
Injecting primitive and string-based values
Let's see the simple example to inject primitive and string-based values. We have created three
files here:
o [Link]
o [Link]
o [Link]
[Link]
It is a simple class containing two fields id and name. There are four constructors and one
method in this class.
1. package [Link];
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. public Employee() {[Link]("def cons");}
8.
9. public Employee(int id) {[Link] = id;}
10.
11. public Employee(String name) { [Link] = name;}
12.
13. public Employee(int id, String name) {
14. [Link] = id;
15. [Link] = name;
16. }
17.
18. void show(){
19. [Link](id+" "+name);
20. }
21.
22. }
[Link]
We are providing the information into the bean by this file. The constructor-arg element invokes
the constructor. In such case, parameterized constructor of int type will be invoked. The value
attribute of constructor-arg element will assign the specified value. The type attribute specifies
that int parameter constructor will be invoked.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="e" class="[Link]">
10. <constructor-arg value="10" type="int"></constructor-arg>
11. </bean>
12.
13. </beans>
[Link]
This class gets the bean from the [Link] file and calls the show method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link].*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)[Link]("e");
14. [Link]();
15.
16. }
17. }
Output:10 null
download this example
Injecting string-based values
If you don't specify the type attribute in the constructor-arg element, by default string type
constructor will be invoked.
1. ....
2. <bean id="e" class="[Link]">
3. <constructor-arg value="10"></constructor-arg>
4. </bean>
5. ....
If you change the bean element as given above, string parameter constructor will be invoked
and the output will be 0 10.
Output:0 10
You may also pass the string literal as following:
1. ....
2. <bean id="e" class="[Link]">
3. <constructor-arg value="Sonoo"></constructor-arg>
4. </bean>
5. ....
Output:0 Sonoo
You may pass integer literal and string both as following
1. ....
2. <bean id="e" class="[Link]">
3. <constructor-arg value="10" type="int" ></constructor-arg>
4. <constructor-arg value="Sonoo"></constructor-arg>
5. </bean>
6. ....
Output:10 Sonoo
Constructor Injection with Dependent Object
If there is HAS-A relationship between the classes, we create the instance of dependent object
(contained object) first then pass it as an argument of the main class constructor. Here, our
scenario is Employee HAS-A Address. The Address class object will be termed as the dependent
object. Let's see the Address class first:
[Link]
This class contains three properties, one constructor and toString() method to return the values
of these object.
1. package [Link];
2.
3. public class Address {
4. private String city;
5. private String state;
6. private String country;
7.
8. public Address(String city, String state, String country) {
9. super();
10. [Link] = city;
11. [Link] = state;
12. [Link] = country;
13. }
14.
15. public String toString(){
16. return city+" "+state+" "+country;
17. }
18. }
[Link]
It contains three properties id, name and address(dependent object) ,two constructors and
show() method to show the records of the current object including the depedent object.
1. package [Link];
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private Address address;//Aggregation
7.
8. public Employee() {[Link]("def cons");}
9.
10. public Employee(int id, String name, Address address) {
11. super();
12. [Link] = id;
13. [Link] = name;
14. [Link] = address;
15. }
16.
17. void show(){
18. [Link](id+" "+name);
19. [Link]([Link]());
20. }
21.
22. }
[Link]
The ref attribute is used to define the reference of another object, such way we are passing the
dependent object as an constructor argument.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="a1" class="[Link]">
10. <constructor-arg value="ghaziabad"></constructor-arg>
11. <constructor-arg value="UP"></constructor-arg>
12. <constructor-arg value="India"></constructor-arg>
13. </bean>
14.
15.
16. <bean id="e" class="[Link]">
17. <constructor-arg value="12" type="int"></constructor-arg>
18. <constructor-arg value="Sonoo"></constructor-arg>
19. <constructor-arg>
20. <ref bean="a1"/>
21. </constructor-arg>
22. </bean>
23.
24. </beans>
[Link]
This class gets the bean from the [Link] file and calls the show method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link].*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)[Link]("e");
14. [Link]();
15.
16. }
17. }
Constructor Injection with Collection Example
We can inject collection values by constructor in spring framework. There can be used three
elements inside the constructor-arg element.
It can be:
1. list
2. set
3. map
Each collection can have string based and non-string based values.
In this example, we are taking the example of Forum where One question can have multiple
answers. There are three pages:
1. [Link]
2. [Link]
3. [Link]
In this example, we are using list that can have duplicate elements, you may use set that have
only unique elements. But, you need to change list to set in the [Link] file and
List to Set in the [Link] file.
[Link]
This class contains three properties, two constructors and displayInfo() method that prints the
information. Here, we are using List to contain the multiple answers.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. public class Question {
7. private int id;
8. private String name;
9. private List<String> answers;
10.
11. public Question() {}
12. public Question(int id, String name, List<String> answers) {
13. super();
14. [Link] = id;
15. [Link] = name;
16. [Link] = answers;
17. }
18.
19. public void displayInfo(){
20. [Link](id+" "+name);
21. [Link]("answers are:");
22. Iterator<String> itr=[Link]();
23. while([Link]()){
24. [Link]([Link]());
25. }
26. }
27.
28. }
[Link]
The list element of constructor-arg is used here to define the list.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="q" class="[Link]">
10. <constructor-arg value="111"></constructor-arg>
11. <constructor-arg value="What is java?"></constructor-arg>
12. <constructor-arg>
13. <list>
14. <value>Java is a programming language</value>
15. <value>Java is a Platform</value>
16. <value>Java is an Island of Indonasia</value>
17. </list>
18. </constructor-arg>
19. </bean>
20.
21. </beans>
[Link]
This class gets the bean from the [Link] file and calls the displayInfo method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Question q=(Question)[Link]("q");
14. [Link]();
15.
16. }
17. }
Constructor Injection with Map Example
In this example, we are using map as the answer that have answer with posted username. Here,
we are using key and value pair both as a string.
Like previous examples, it is the example of forum where one question can have multiple
answers.
[Link]
This class contains three properties, two constructors and displayInfo() method to display the
information.
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. public class Question {
8. private int id;
9. private String name;
10. private Map<String,String> answers;
11.
12. public Question() {}
13. public Question(int id, String name, Map<String, String> answers) {
14. super();
15. [Link] = id;
16. [Link] = name;
17. [Link] = answers;
18. }
19.
20. public void displayInfo(){
21. [Link]("question id:"+id);
22. [Link]("question name:"+name);
23. [Link]("Answers....");
24. Set<Entry<String, String>> set=[Link]();
25. Iterator<Entry<String, String>> itr=[Link]();
26. while([Link]()){
27. Entry<String,String> entry=[Link]();
28. [Link]("Answer:"+[Link]()+" Posted By:"+[Link]());
29. }
30. }
31. }
[Link]
The entry attribute of map is used to define the key and value information.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="q" class="[Link]">
10. <constructor-arg value="11"></constructor-arg>
11. <constructor-arg value="What is Java?"></constructor-arg>
12. <constructor-arg>
13. <map>
14. <entry key="Java is a Programming Language" value="Ajay Kumar"></entry>
15. <entry key="Java is a Platform" value="John Smith"></entry>
16. <entry key="Java is an Island" value="Raj Kumar"></entry>
17. </map>
18. </constructor-arg>
19. </bean>
20.
21. </beans>
[Link]
This class gets the bean from the [Link] file and calls the displayInfo() method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Question q=(Question)[Link]("q");
14. [Link]();
15.
16. }
17. }
Dependency Injection by setter method
We can inject the dependency by setter method also. The <property> subelement
of <bean> is used for setter injection. Here we are going to inject
1. primitive and String-based values
2. Dependent object (contained object)
3. Collection values etc.
Injecting primitive and string-based values by setter method
Let's see the simple example to inject primitive and string-based values by setter method. We
have created three files here:
o [Link]
o [Link]
o [Link]
[Link]
It is a simple class containing three fields id, name and city with its setters and getters and a
method to display these informations.
1. package [Link];
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private String city;
7.
8. public int getId() {
9. return id;
10. }
11. public void setId(int id) {
12. [Link] = id;
13. }
14. public String getName() {
15. return name;
16. }
17. public void setName(String name) {
18. [Link] = name;
19. }
20.
21. public String getCity() {
22. return city;
23. }
24. public void setCity(String city) {
25. [Link] = city;
26. }
27. void display(){
28. [Link](id+" "+name+" "+city);
29. }
30.
31. }
[Link]
We are providing the information into the bean by this file. The property element invokes the
setter method. The value subelement of property will assign the specified value.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="obj" class="[Link]">
10. <property name="id">
11. <value>20</value>
12. </property>
13. <property name="name">
14. <value>Arun</value>
15. </property>
16. <property name="city">
17. <value>ghaziabad</value>
18. </property>
19.
20. </bean>
21.
22. </beans>
[Link]
This class gets the bean from the [Link] file and calls the display method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link].*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee e=(Employee)[Link]("obj");
14. [Link]();
15.
16. }
17. }
Setter Injection with Dependent Object Example
Like Constructor Injection, we can inject the dependency of another bean using setters. In such
case, we use property element. Here, our scenario is Employee HAS-A Address. The Address
class object will be termed as the dependent object. Let's see the Address class first:
[Link]
This class contains four properties, setters and getters and toString() method.
1. package [Link];
2.
3. public class Address {
4. private String addressLine1,city,state,country;
5.
6. //getters and setters
7.
8. public String toString(){
9. return addressLine1+" "+city+" "+state+" "+country;
10. }
[Link]
It contains three properties id, name and address(dependent object) , setters and getters with
displayInfo() method.
1. package [Link];
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private Address address;
7.
8. //setters and getters
9.
10. void displayInfo(){
11. [Link](id+" "+name);
12. [Link](address);
13. }
14. }
[Link]
The ref attribute of property elements is used to define the reference of another bean.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="address1" class="[Link]">
10. <property name="addressLine1" value="51,Lohianagar"></property>
11. <property name="city" value="Ghaziabad"></property>
12. <property name="state" value="UP"></property>
13. <property name="country" value="India"></property>
14. </bean>
15.
16. <bean id="obj" class="[Link]">
17. <property name="id" value="1"></property>
18. <property name="name" value="Sachin Yadav"></property>
19. <property name="address" ref="address1"></property>
20. </bean>
21.
22. </beans>
[Link]
This class gets the bean from the [Link] file and calls the displayInfo() method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class Test {
11. public static void main(String[] args) {
12. Resource r=new ClassPathResource("[Link]");
13. BeanFactory factory=new XmlBeanFactory(r);
14.
15. Employee e=(Employee)[Link]("obj");
16. [Link]();
17.
18. }
19. }
Setter Injection with Collection Example
We can inject collection values by setter method in spring framework. There can be used three
elements inside the property element.
It can be:
1. list
2. set
3. map
Each collection can have string based and non-string based values.
In this example, we are taking the example of Forum where One question can have multiple
answers. There are three pages:
1. [Link]
2. [Link]
3. [Link]
In this example, we are using list that can have duplicate elements, you may use set that have
only unique elements. But, you need to change list to set in the [Link] file and
List to Set in the [Link] file.
[Link]
This class contains three properties with setters and getters and displayInfo() method that prints
the information. Here, we are using List to contain the multiple answers.
1. package [Link];
2. import [Link];
3. import [Link];
4.
5. public class Question {
6. private int id;
7. private String name;
8. private List<String> answers;
9.
10. //setters and getters
11.
12. public void displayInfo(){
13. [Link](id+" "+name);
14. [Link]("answers are:");
15. Iterator<String> itr=[Link]();
16. while([Link]()){
17. [Link]([Link]());
18. }
19. }
20.
21. }
[Link]
The list element of constructor-arg is used here to define the list.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="q" class="[Link]">
10. <property name="id" value="1"></property>
11. <property name="name" value="What is Java?"></property>
12. <property name="answers">
13. <list>
14. <value>Java is a programming language</value>
15. <value>Java is a platform</value>
16. <value>Java is an Island</value>
17. </list>
18. </property>
19. </bean>
20.
21. </beans>
[Link]
This class gets the bean from the [Link] file and calls the displayInfo method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Question q=(Question)[Link]("q");
14. [Link]();
15.
16. }
17. }
Setter Injection with Map Example
In this example, we are using map as the answer for a question that have answer as the key and
username as the value. Here, we are using key and value pair both as a string.
Like previous examples, it is the example of forum where one question can have multiple
answers.
[Link]
This class contains three properties, getters & setters and displayInfo() method to display the
information.
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. public class Question {
8. private int id;
9. private String name;
10. private Map<String,String> answers;
11.
12. //getters and setters
13.
14. public void displayInfo(){
15. [Link]("question id:"+id);
16. [Link]("question name:"+name);
17. [Link]("Answers....");
18. Set<Entry<String, String>> set=[Link]();
19. Iterator<Entry<String, String>> itr=[Link]();
20. while([Link]()){
21. Entry<String,String> entry=[Link]();
22. [Link]("Answer:"+[Link]()+" Posted By:"+[Link]());
23. }
24. }
25. }
[Link]
The entry attribute of map is used to define the key and value information.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xmlns:p="[Link]
6. xsi:schemaLocation="[Link]
7. [Link]
8.
9. <bean id="q" class="[Link]">
10. <property name="id" value="1"></property>
11. <property name="name" value="What is Java?"></property>
12. <property name="answers">
13. <map>
14. <entry key="Java is a programming language" value="Sonoo Jaiswal"></entry>
15. <entry key="Java is a Platform" value="Sachin Yadav"></entry>
16. </map>
17. </property>
18. </bean>
19.
20. </beans>
[Link]
This class gets the bean from the [Link] file and calls the displayInfo() method.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource r=new ClassPathResource("[Link]");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Question q=(Question)[Link]("q");
14. [Link]();
15.
16. }
17. }
What is Auto Scanning:
Normally you declare all the beans or components in XML bean configuration file, so that Spring
container can detect and register your beans or components. Actually, Spring is able to auto
scan, detect and instantiate your beans from pre-defined project package, no more tedious
beans declaration in in XML file.
There are 4 types of auto components scan annotation types
@Component – Indicates a auto scan component.
@Repository – Indicates DAO component in the persistence layer.
@Service – Indicates a Service component in the business layer.
@Controller – Indicates a controller component in the presentation layer.