UNIT-1
Spring 5 Basics
Spring:
Spring Framework was developed by Rod Johnson in 2003. Spring framework makes the
easy development of JavaEE application.
Spring Framework:
Spring is a lightweight framework. It can be thought of as a framework of
frameworks because it provides support for various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc. It can be defined as a structure where we find solution for various
technical problems. The Spring framework comprises of several modules such as IOC, AOP,
DAO, Context, ORM, WEB MVC etc.
Spring Modules:
The Spring framework comprises of many modules such as core, beans, context, expression
language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web,
Servlet, Struts etc. These modules are grouped into Test, Core Container, AOP, Aspects,
Instrumentation, Data Access / Integration, Web (MVC / Remoting) as displayed in the
following diagram.
Test
This layer provides support of testing with JUnit and TestNG.
Spring Core Container
The Spring Core container contains core, beans, context and expression language (EL)
modules.
Core and Beans
These modules provide IOC and Dependency Injection features.
Context
This module supports internationalization (I18N), EJB, JMS, Basic Remoting.
Expression Language
It is an extension to the EL defined in JSP. It provides support to setting and getting property
values, method invocation, accessing collections and indexers, named variables, logical and
arithmetic operators, retrieval of objects by name etc.
AOP, Aspects and Instrumentation
These modules support aspect oriented programming implementation where you can use
Advices, Pointcuts etc. to decouple the code.
The aspects module provides support to integration with AspectJ.
The instrumentation module provides support to class instrumentation and classloader
implementations.
Data Access / Integration
This group comprises of JDBC, ORM, OXM, JMS and Transaction modules. These modules
basically provide support to interact with the database.
Web
This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet. These modules
provide support to create web application.
Spring Example
1. Steps to create spring application
Here, we are going to learn the simple steps to create the first spring application. To run this
application, we are not using any IDE. We are simply using the command prompt. Let's see
the simple steps to create the spring application
o create the class
o create the xml file to provide the values
o create the test class
o Load the spring jar files
o Run the test class
Steps to create spring application
Let's see the 5 steps to create the first spring application.
1) Create Java class
This is the simple java bean class containing the name property only.
1. package com.javatpoint;
2.
3. public class Student {
4. private String name;
5.
6. public String getName() {
7. return name;
8. }
9.
10. public void setName(String name) {
11. this.name = name;
12. }
13.
14. public void displayInfo(){
15. System.out.println("Hello: "+name);
16. }
17. }
This is simple bean class, containing only one property name with its getters and setters
method. This class contains one extra method named displayInfo() that prints the student
name by the hello message.
2) Create the xml file
In case of myeclipse IDE, you don't need to create the xml file as myeclipse does this for
yourselves. Open the applicationContext.xml file, and write the following code:
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans
3. xmlns="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="studentbean" class="com.javatpoint.Student">
10. <property name="name" value="Vimal Jaiswal"></property>
11. </bean>
12.
13. </beans>
The bean element is used to define the bean for the given class. The property subelement of
bean specifies the property of the Student class named name. The value specified in the
property element will be set in the Student class object by the IOC container.
3) Create the test class
Create the java class e.g. Test. Here we are getting the object of Student class from the IOC
container using the getBean() method of BeanFactory. Let's see the code of test class.
1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.ClassPathResource;
6. import org.springframework.core.io.Resource;
7.
8. public class Test {
9. public static void main(String[] args) {
10. Resource resource=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(resource);
12.
13. Student student=(Student)factory.getBean("studentbean");
14. student.displayInfo();
15. }
16. }
The Resource object represents the information of applicationContext.xml file. The Resource
is the interface and the ClassPathResource is the implementation class of the Reource
interface. The BeanFactory is responsible to return the bean. The XmlBeanFactory is the
implementation class of the BeanFactory. There are many methods in the BeanFactory
interface. One method is getBean(), which returns the object of the associated class.
4) Load the jar files required for spring framework
There are mainly three jar files required to run this application.
o org.springframework.core-3.0.1.RELEASE-A
o com.springsource.org.apache.commons.logging-1.1.1
o org.springframework.beans-3.0.1.RELEASE-A
For the future use, You can download the required jar files for spring core application.
download the core jar files for spring
download the all jar files for spring including core, web, aop, mvc, j2ee, remoting, oxm, jdbc,
orm etc.
To run this example, you need to load only spring core jar files.
5) Run the test class
Now run the Test class. You will get the output Hello: Vimal Jaiswal.
Configuring IOC Container using Java-based Configuration:
Spring - Java Based Configuration:
Java-based configuration option enables you to write most of your Spring configuration
without XML but with the help of few Java-based annotations explained in this chapter.
@Configuration & @Bean Annotations
Annotating a class with the @Configuration indicates that the class can be used by the
Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that
a method annotated with @Bean will return an object that should be registered as a bean in
the Spring application context. The simplest possible @Configuration class would be as
follows −
package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
The above code will be equivalent to the following XML configuration −
<beans>
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" />
</beans>
Here, the method name is annotated with @Bean works as bean ID and it creates and returns
the actual bean. Your configuration class can have a declaration for more than one @Bean.
Once your configuration classes are defined, you can load and provide them to Spring
container using AnnotationConfigApplicationContext as follows −
public static void main(String[] args) {
ApplicationContext ctx = new
AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
You can load various configuration classes as follows −
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
ctx.refresh();
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
Example
Let us have a working Eclipse IDE in place and take the following steps to create a Spring
application −
Steps Description
Create a project with a name SpringExample and create a
1
package com.tutorialspoint under the src folder in the created project.
Add required Spring libraries using Add External JARs option as explained in the Spring
2
Hello World Example chapter.
3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from
your Java installation directory and ASM.jar library which can be downloaded
from asm.ow2.org.
Create Java classes HelloWorldConfig, HelloWorld and MainApp under
4
the com.tutorialspoint package.
The final step is to create the content of all the Java files and Bean Configuration file and
5
run the application as explained below.
Here is the content of HelloWorldConfig.java file
package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
Here is the content of HelloWorld.java file
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
Following is the content of the MainApp.java file
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
}
Once you are done creating all the source files and adding the required additional libraries, let
us run the application. You should note that there is no configuration file required. If
everything is fine with your application, it will print the following message −
Your Message : Hello World!
Injecting Bean Dependencies
When @Beans have dependencies on one another, expressing that the dependency is as
simple as having one bean method calling another as follows −
package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}
Here, the foo bean receives a reference to bar via the constructor injection.
Dependency Injection in Spring :
1. Dependency Injection in Spring
2. Dependency Lookup
3. Dependency Injection
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. To understand the DI better, Let's
understand the Dependency Lookup (DL) first:
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There can
be various ways to get the resource for example:
1. A obj = new AImpl();
In such way, we get the resource(instance of A class) directly by new keyword. Another way
is factory method:
1. A obj = A.getA();
This way, we get the resource (instance of A class) by calling the static factory method
getA().
Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:
1. Context ctx = new InitialContext();
2. Context environmentCtx = (Context) ctx.lookup("java:comp/env");
3. A obj = (A)environmentCtx.lookup("A");
There can be various ways to get the resource to obtain the resource. Let's see the problem in
this approach.
Problems of Dependency Lookup
There are mainly two problems of dependency lookup.
o Tight coupling The dependency lookup approach makes the code tightly coupled. If
resource is changed, we need to perform a lot of modification in the code.
o Not easy for testing This approach creates a lot of problems while testing the
application especially in black box testing.
Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the programs.
In such case we provide the information from the external source such as XML file. It makes
our code loosely coupled and easier for testing. In such case we write the code as:
1. class Employee{
2. Address address;
3.
4. Employee(Address address){
5. this.address=address;
6. }
7. public void setAddress(Address address){
8. this.address=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
1. Dependency Injection by constructor
2. Injecting primitive and string-based values
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 Employee.java
o applicationContext.xml
o Test.java
Employee.java
It is a simple class containing two fields id and name. There are four constructors and one
method in this class.
1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6.
7. public Employee() {System.out.println("def cons");}
8.
9. public Employee(int id) {this.id = id;}
10.
11. public Employee(String name) { this.name = name;}
12.
13. public Employee(int id, String name) {
14. this.id = id;
15. this.name = name;
16. }
17.
18. void show(){
19. System.out.println(id+" "+name);
20. }
21.
22. }
applicationContext.xml
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="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="e" class="com.javatpoint.Employee">
10. <constructor-arg value="10" type="int"></constructor-arg>
11. </bean>
12.
13. </beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee s=(Employee)factory.getBean("e");
14. s.show();
15.
16. }
17. }
Output:10 null
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="com.javatpoint.Employee">
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="com.javatpoint.Employee">
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="com.javatpoint.Employee">
3. <constructor-arg value="10" type="int" ></constructor-arg>
4. <constructor-arg value="Sonoo"></constructor-arg>
5. </bean>
6. ....
Output:10 Sonoo
Dependency Injection by setter method
1. Dependency Injection by constructor
2. Injecting primitive and string-based values
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 Employee.java
o applicationContext.xml
o Test.java
Employee.java
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 com.javatpoint;
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. this.id = id;
13. }
14. public String getName() {
15. return name;
16. }
17. public void setName(String name) {
18. this.name = name;
19. }
20.
21. public String getCity() {
22. return city;
23. }
24. public void setCity(String city) {
25. this.city = city;
26. }
27. void display(){
28. System.out.println(id+" "+name+" "+city);
29. }
30.
31. }
applicationContext.xml
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="http://www.springframework.org/schema/beans"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xmlns:p="http://www.springframework.org/schema/p"
6. xsi:schemaLocation="http://www.springframework.org/schema/beans
7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
8.
9. <bean id="obj" class="com.javatpoint.Employee">
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>
Test.java
This class gets the bean from the applicationContext.xml file and calls the display method.
1. package com.javatpoint;
2.
3. import org.springframework.beans.factory.BeanFactory;
4. import org.springframework.beans.factory.xml.XmlBeanFactory;
5. import org.springframework.core.io.*;
6.
7. public class Test {
8. public static void main(String[] args) {
9.
10. Resource r=new ClassPathResource("applicationContext.xml");
11. BeanFactory factory=new XmlBeanFactory(r);
12.
13. Employee e=(Employee)factory.getBean("obj");
14. s.display();
15.
16. }
17. }
Output: 20 Arun Ghaziabad
Spring 5 auto scanning using @Component annotation and XML
configuration
Spring framework has the functionality to auto-detect or auto scan the bean’s classes for
injection using @Component annotation. @Component is a generic stereotype for any Spring-
managed component. In the most of the previous example, we use the XML to specify the
configuration metadata that produces each BeanDefinition within the Spring container manually.
For auto scanning of beans, we need to add the context namespace schema to the root beans
tag and scan the package. See the below configuration.
<beans
//...
xmlns:context="http://www.springframework.org/schema/context"
//...
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- scan the package -->
<context:component-scan base-package="org.websparrow.beans" />
<!-- activate annotations -->
<context:annotation-config />
</beans>
Whenever Spring container will load the configuration file, it will create the object of
annotated beans.
Note: It is application only for secondary type dependency injection. For primitive type we
have to inject it manually.
In this example, I have used the @Component annotation for auto scanning
and @Autowired annotation for automatic dependency injection. Let’s see the complete
example.
Spring Beans
Create the two bean classes. In the State class declare a primitive type variable.
State.java
package org.websparrow.beans;
public class State {
// Generate setters and getters...
private String stateName;
}
And in Country class, create an object of State class which is a secondary type. Use
the @Component annotation at the top of the class name.
Country.java
package org.websparrow.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Country {
@Autowired
private State state;
public void display() {
System.out.println("State name is: " + state.getStateName());
}
}
Spring Beans Configuration
In the configuration add context schema to the root tag bean and scan the package
using <context:component-scan base-package="org.websparrow.beans" /> and activate the
annotations.
spring.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- scan the package -->
<context:component-scan base-package="org.websparrow.beans" />
<!-- activate annotations -->
<context:annotation-config />
<!-- manual injection for primitive type -->
<bean id="s1" class="org.websparrow.beans.State">
<property name="stateName" value="Uttar Pradesh" />
</bean>
</beans>
Copy
How does it work?
There is a question that nocks your mind that how is works or what is the flow of auto-
scanning. So whenever Spring container will the read the XML configuration, it will scan all
the package that you defined in <context:component-scan base-
package="org.websparrow.beans" /> and automatically creates the objects of all beans where
you annotated by @Component.
Run it
To test it, load the configuration file use J2EE container and run it. But here we don’t have
any reference bean id name, pass the class name Country.class as reference bean id.
Test.java
package org.websparrow.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.websparrow.beans.Country;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
Country c = (Country) context.getBean(Country.class);
c.display();
}
}
Output:
The following result will display on your console log.
State name is: Uttar Pradesh