0% found this document useful (0 votes)
10 views

Spring Framework (1)

The Spring Framework is a widely used Java EE framework that facilitates the development of reliable applications through its core concepts of Dependency Injection (DI), Inversion of Control (IoC), and Aspect-Oriented Programming (AOP). It consists of various modules for core functionalities, web applications, data access, and testing, allowing developers to choose specific components for their applications. The document also discusses the advantages and disadvantages of using Java Dependency Injection, along with practical examples of implementing DI using both annotations and XML configuration.

Uploaded by

aravindhkumar311
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Spring Framework (1)

The Spring Framework is a widely used Java EE framework that facilitates the development of reliable applications through its core concepts of Dependency Injection (DI), Inversion of Control (IoC), and Aspect-Oriented Programming (AOP). It consists of various modules for core functionalities, web applications, data access, and testing, allowing developers to choose specific components for their applications. The document also discusses the advantages and disadvantages of using Java Dependency Injection, along with practical examples of implementing DI using both annotations and XML configuration.

Uploaded by

aravindhkumar311
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Spring Framework

Spring Framework is one of the most popular Java EE frameworks. In this article, we will learn
about the following:

• Spring framework architecture

• Core components of Spring

What is Spring Framework?


Spring is one of the most popular frameworks for Java enterprise edition. Developers all over the
world use Spring for developing reliable and high-quality applications. The spring framework was
designed by Rod Johnson. Since then Spring has become an alternative technology in Java world
for the EJB model. You can create different kinds of applications using the spring framework.

Spring Core Concepts - DI, IoC, AOP

• It is impossible to understand what is Spring Framework without understanding what


is Dependency Injection and Inversion of Control. Dependency Injection also called as DI,
is one of the types of Inversion of Control (IoC).

• Inversion of Control - this is the principle of object-oriented programming, in which


objects of the program do not depend on concrete implementations of other objects, but
may have knowledge about their abstractions (interfaces) for later interaction.

• Dependency Injection - is a composition of structural design patterns, in which for each


function of the application there is one, a conditionally independent object (service) that
can have the need to use other objects (dependencies) known to it by interfaces.
Dependencies are transferred (implemented) to the service at the time of its creation. This
is a situation where we introduce an element of one class into another. In practice, DI is
implemented by passing parameters to the constructor or using setters. Libraries that
implement this approach are also called IoC containers.

• Aspect oriented programming - a programming paradigm that allows you to distinguish


cross-through (functional) functionality in application. These functions, which span
multiple application nodes, are called cross-cutting concerns and these cross-cutting
notes are separated from the immediate business logic of the application. In OOP, the key
unit is the class, while in AOP, the key element is the aspect. DI helps to separate
application classes into separate modules, and AOP helps to separate cross-cutting
concerns from the objects they affect.

Spring Framework Architecture


Spring Framework is divided into a number of separate modules, which allows you to decide
which ones to use in your application. The below image illustrates the most important modules of
Spring Framework architecture.

Let’s look into spring ecosystem modules one by one.

Spring Framework Core Components


The Core container from Spring consists of four modules: SpEL , Context, Core, Beans.
Description for these elements are as follows:

1. The SpEL module provides a powerful expression language for manipulating objects during
execution.

2. Context is built on the basis of Beans and Core and allows you to access any object that is
defined in the settings. The key element of the Context module is the ApplicationContext
interface.

3. The Core module provides key parts of the framework including IoC and DI properties.

4. The Bean module is responsible for creating and managing Spring Beans - is application
context structure unit.

Spring Framework Web

Spring framework Web layer consists of Web, Web-MVC, Web-Socket, Web-Portlet etc.

1. The Web module provides functions such as downloading files, creating web application,
rest web service etc.

2. Web-MVC contains a Spring MVC implementation for web applications.

3. Web-Socket provides support for communication between the client and the server, using
Web-Sockets in web applications.

4. Web-Portlet provides MVC implementation with portlet environment

Spring Framework Data Access

The Data Access/Integration container consists of JDBC, ORM, OXM, JMS and the Transactions
module.

1. JDBC provides an abstract layer of JDBC and eliminates the need for the developer to
manually register the monotonous code associated with connecting to the database.

2. Spring ORM provides integration with popular ORMs such as Hibernate, JDO, which are
implementations of JPA.

3. The OXM module is responsible for linking the Object / XML - XMLBeans, JAXB, etc.

4. The JMS (Java Messaging Service) module is responsible for creating, sending and receiving
messages.

5. Transactions supports transaction management for classes that implement certain


methods and POJOs.
Miscellaneous Modules

Spring also includes a number of other important modules, such as AOP, Aspects,
Instrumentation, Messaging, and Test.

1. AOP implements aspect-oriented programming and allows using the entire arsenal of AOP
capabilities.

2. The Aspects module provides integration with AspectJ, which is also a powerful AOP
framework.

3. Instrumentation is responsible for supporting class instrumentation and class loader,


which are used in server applications.

4. The Messaging module provides STOMP support.

5. Finally, the Test module provides testing using TestNG or the JUnit Framework.

Java Dependency Injection


Java Dependency Injection design pattern allows us to remove the hard-coded dependencies
and make our application loosely coupled, extendable and maintainable. We can
implement dependency injection in java to move the dependency resolution from compile-time
to runtime.

Java Dependency Injection


Java Dependency injection seems hard to grasp with theory, so I would take a simple example and
then we will see how to use dependency injection pattern to achieve loose coupling and
extendability in the application. Let’s say we have an application where we
consume EmailService to send emails. Normally we would implement this like below.
EmailService class holds the logic to send an email message to the recipient email address.
Our application code will be like below.

Our client code that will use MyApplication class to send email messages will be like below.

At first look, there seems nothing wrong with the above implementation. But above code logic has
certain limitations.

• MyApplication class is responsible to initialize the email service and then use it. This leads
to hard-coded dependency. If we want to switch to some other advanced email service in
the future, it will require code changes in MyApplication class. This makes our application
hard to extend and if email service is used in multiple classes then that would be even
harder.

• If we want to extend our application to provide an additional messaging feature, such as


SMS or Facebook message then we would need to write another application for that. This
will involve code changes in application classes and in client classes too.

• Testing the application will be very difficult since our application is directly creating the
email service instance. There is no way we can mock these objects in our test classes.

One can argue that we can remove the email service instance creation
from MyApplication class by having a constructor that requires email service as an
argument.

But in this case, we are asking client applications or test classes to initializing the email
service that is not a good design decision. Now let’s see how we can apply java dependency
injection pattern to solve all the problems with the above implementation. Dependency
Injection in java requires at least the following:

1. Service components should be designed with base class or interface. It’s better to prefer
interfaces or abstract classes that would define contract for the services.

2. Consumer classes should be written in terms of service interface.

3. Injector classes that will initialize the services and then the consumer classes.
Java Dependency Injection - Service Components

For our case, we can have MessageService that will declare the contract for service
implementations.

Now let’s say we have Email and SMS services that implement the above interfaces.

Our dependency injection java services are ready and now we can write our consumer class.
Java Dependency Injection - Service Consumer

We are not required to have base interfaces for consumer classes but I will have
a Consumer interface declaring contract for consumer classes.

My consumer class implementation is like below.

Notice that our application class is just using the service. It does not initialize the service that
leads to better “separation of concerns”. Also use of service interface allows us to easily test the
application by mocking the MessageService and bind the services at runtime rather than compile
time. Now we are ready to write java dependency injector classes that will initialize the service
and also consumer classes.
Java Dependency Injection - Injectors Classes

Now for every service, we will have to create injector classes like below.

-------------------------------------------------------------------------------------------------------------
As you can see that our application classes are responsible only for using the service. Service
classes are created in injectors. Also if we have to further extend our application to allow facebook
messaging, we will have to write Service classes and injector classes only. So dependency
injection implementation solved the problem with hard-coded dependency and helped us in
making our application flexible and easy to extend.

One of the best example of setter dependency injection is Struts2 Servlet API Aware interfaces.
Whether to use Constructor based dependency injection or setter based is a design decision and
depends on your requirements. For example, if my application can’t work at all without the service
class then I would prefer constructor based DI or else I would go for setter method based DI to use
it only when it’s really needed. Dependency Injection in Java is a way to achieve Inversion of
control (IoC) in our application by moving objects binding from compile time to runtime. We can
achieve IoC through Factory Pattern, Template Method Design Pattern, Strategy Pattern and
Service Locator pattern too. Spring Dependency Injection, Google Guice and Java EE
CDI frameworks facilitate the process of dependency injection through use of Java Reflection
API and java annotations. All we need is to annotate the field, constructor or setter method and
configure them in configuration xml files or classes.

Benefits of Java Dependency Injection


Some of the benefits of using Dependency Injection in Java are:

• Separation of Concerns

• Boilerplate Code reduction in application classes because all work to initialize


dependencies is handled by the injector component

• Configurable components makes application easily extendable

• Unit testing is easy with mock objects

Disadvantages of Java Dependency Injection

Java Dependency injection has some disadvantages too:

• If overused, it can lead to maintenance issues because the effect of changes are known at
runtime.

• Dependency injection in java hides the service class dependencies that can lead to
runtime errors that would have been caught at compile time
This tutorial is aimed to provide details about Spring Dependency Injection example with both
annotation based configuration and XML file based configuration. I will also provide JUnit test case
example for the application, since easy testability is one of the major benefits of dependency
injection. I have created spring-dependency-injection maven project whose structure looks like

below image. Let’s look at each of the


components one by one.

Spring Dependency Injection - Maven Dependencies

I have added Spring and JUnit maven dependencies in pom.xml file, final pom.xml code is below.
Current stable version of Spring Framework is 4.0.0.RELEASE and JUnit current version is 4.8.1, if
you are using any other versions then there might be a small chance that the project will need
some change. If you will build the project, you will notice some other jars are also added to maven
dependencies because of transitive dependencies, just like above image.

Spring Dependency Injection - Service Classes

Let’s say we want to send email message and twitter message to the users. For dependency
injection, we need to have a base class for the services. So I have MessageService interface with
single method declaration for sending message.
Now we will have actual implementation classes to send email and twitter message.

Now that our services are ready, we can move on to Component classes that will consume the
service.

Spring Dependency Injection - Component Classes

Let’s write a consumer class for above services. We will have two consumer classes - one with
Spring annotations for autowiring and another without annotation and wiring configuration will be
provided in the XML configuration file.
Few important points about MyApplication class:

• @Component annotation is added to the class, so that when Spring framework will scan
for the components, this class will be treated as component. @Component annotation can
be applied only to the class and it’s retention policy is Runtime. If you are not not familiar
with Annotations retention policy, I would suggest you to read java annotations tutorial.
• @Autowired annotation is used to let Spring know that autowiring is required. This can be
applied to field, constructor and methods. This annotation allows us to implement
constructor-based, field-based or method-based dependency injection in our
components.

• For our example, I am using method-based dependency injection. You can uncomment the
constructor method to switch to constructor based dependency injection.

Now let’s write similar class without annotations.


A simple application class consuming the service. For XML based configuration, we can use
implement either constructor-based spring dependency injection or method-based spring
dependency injection. Note that method-based and setter-based injection approaches are same,
it’s just that some prefer calling it setter-based and some call it method-based.

Spring Dependency Injection Configuration with Annotations

For annotation based configuration, we need to write a Configurator class that will be used to
inject the actual implementation bean to the component property.

Some important points related to above class are:

• @Configuration annotation is used to let Spring know that it’s a Configuration class.
• @ComponentScan annotation is used with @Configuration annotation to specify the
packages to look for Component classes.

• @Bean annotation is used to let Spring framework know that this method should be used
to get the bean implementation to inject in Component classes.

Let’s write a simple program to test our annotation based Spring Dependency Injection example.

AnnotationConfigApplicationContext is the implementation


of AbstractApplicationContext abstract class and it’s used for autowiring the services to
components when annotations are used. AnnotationConfigApplicationContext constructor takes
Class as argument that will be used to get the bean implementation to inject in component
classes. getBean(Class) method returns the Component object and uses the configuration for
autowiring the objects. Context objects are resource intensive, so we should close them when we
are done with it. When we run above program, we get below output.

Dec 16, 2013 11:49:20 PM org.springframework.context.support.AbstractApplicationContext


prepareRefresh
INFO: Refreshing
org.springframework.context.annotation.AnnotationConfigApplicationContext@3067ed13:
startup date [Mon Dec 16 23:49:20 PST 2013]; root of context hierarchy

Email Sent to [email protected] with Message=Hi Pankaj

Dec 16, 2013 11:49:20 PM org.springframework.context.support.AbstractApplicationContext


doClose

INFO: Closing
org.springframework.context.annotation.AnnotationConfigApplicationContext@3067ed13:
startup date [Mon Dec 16 23:49:20 PST 2013]; root of context hierarchy

Spring Dependency Injection XML Based Configuration

We will create Spring configuration file with below data, file name can be anything.
applicationContext.xml code:
Notice that above XML contains configuration for both constructor-based and setter-based spring
dependency injection. Since MyXMLApplication is using setter method for injection, the bean
configuration contains property element for injection. For constructor based injection, we have to
use constructor-arg element. The configuration XML file is placed in the source directory, so it will
be in the classes directory after build. Let’s see how to use XML based configuration with a simple
program.

ClassPathXmlApplicationContext is used to get the ApplicationContext object by providing the


configuration files location. It has multiple overloaded constructors and we can provide multiple
config files also. Rest of the code is similar to annotation based configuration test program, the
only difference is the way we get the ApplicationContext object based on our configuration choice.
When we run above program, we get following output.

Dec 17, 2013 12:01:23 AM org.springframework.context.support.AbstractApplicationContext


prepareRefresh

INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@4eeaabad: startup date
[Tue Dec 17 00:01:23 PST 2013]; root of context hierarchy

Dec 17, 2013 12:01:23 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader


loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [applicationContext.xml]

Twitter message Sent to [email protected] with Message=Hi Pankaj

Dec 17, 2013 12:01:23 AM org.springframework.context.support.AbstractApplicationContext


doClose

INFO: Closing
org.springframework.context.support.ClassPathXmlApplicationContext@4eeaabad: startup date
[Tue Dec 17 00:01:23 PST 2013]; root of context hierarchy

Notice that some of the output is written by Spring Framework. Since Spring Framework uses log4j
for logging purpose and I have not configured it, the output is getting written to console.

Spring Dependency Injection JUnit Test Case

One of the major benefit of dependency injection in spring is the ease of having mock service
classes rather than using actual services. So I have combined all of the learning from above and
written everything in a single JUnit 4 test class for dependency injection in spring.
The class is annotated with @Configuration and @ComponentScan annotation
because getMessageService() method returns the MessageService mock implementation. That’s
why getMessageService() is annotated with @Bean annotation. Since I am
testing MyApplication class that is configured with annotation, I am
using AnnotationConfigApplicationContext and creating it’s object in the setUp() method. The
context is getting closed in tearDown() method. test() method code is just getting the component
object from context and testing it. Do you wonder how Spring Framework does the autowiring and
calling the methods that are unknown to Spring Framework. It’s done with the heavy use of Java
Reflection that we can use to analyze and modify the behaviors of the classes at runtime.

Spring Bean Scopes allows us to have more granular control of the bean instances creation.
Sometimes we want to create bean instance as singleton but in some other cases we might want
it to be created on every request or once in a session.
Spring IoC, Spring Bean Example
Spring Framework is built on the Inversion of Control principle. Dependency injection is the
technique to implement IoC in applications

Today we will look into Spring IoC Container. We will also go through Spring Bean. Below is the
table to contents for quick navigation to different sections of Spring IoC tutorial.

1. Spring IoC

2. Spring Bean

3. Spring Bean Scopes

4. Spring Bean Configuration

5. Spring IoC and Spring Bean Example

1. XML Based Spring Bean Configuration

2. Annotation Based Spring Bean Configuration

3. Java Based Spring Bean Configuration

Spring IoC Container


Spring IoC is the mechanism to achieve loose-coupling between Objects dependencies. To
achieve loose coupling and dynamic binding of the objects at runtime, objects dependencies are
injected by other assembler objects. Spring IoC container is the program
that injects dependencies into an object and make it ready for our use. We have already looked
how we can use Spring Dependency Injection to implement IoC in our applications. Spring IoC
container classes are part
of org.springframework.beans and org.springframework.context packages. Spring IoC container
provides us different ways to decouple the object dependencies. BeanFactory is the root interface
of Spring IoC container. ApplicationContext is the child interface of BeanFactory interface that
provide Spring AOP features, i18n etc. Some of the useful child-interfaces
of ApplicationContext are ConfigurableApplicationContext and WebApplicationContext. Spring
Framework provides a number of useful ApplicationContext implementation classes that we can
use to get the spring context and then the Spring Bean. Some of the useful ApplicationContext
implementations that we use are;
• AnnotationConfigApplicationContext: If we are using Spring in standalone java
applications and using annotations for Configuration, then we can use this to initialize the
container and get the bean objects.

• ClassPathXmlApplicationContext: If we have spring bean configuration xml file in


standalone application, then we can use this class to load the file and get the container
object.

• FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext


except that the xml configuration file can be loaded from anywhere in the file system.

• AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web


applications.

Usually, if you are working on Spring MVC application and your application is configured to use
Spring Framework, Spring IoC container gets initialized when the application starts and when a
bean is requested, the dependencies are injected automatically. However, for a standalone
application, you need to initialize the container somewhere in the application and then use it to
get the spring beans.

Spring Bean

Spring Bean is nothing special, any object in the Spring framework that we initialize through Spring
container is called Spring Bean. Any normal Java POJO class can be a Spring Bean if it’s configured
to be initialized via container by providing configuration metadata information.

Spring Bean Scopes

There are five scopes defined for Spring Beans.

1. singleton - Only one instance of the bean will be created for each container. This is the
default scope for the spring beans. While using this scope, make sure bean doesn’t have
shared instance variables otherwise it might lead to data inconsistency issues.

2. prototype - A new instance will be created every time the bean is requested.

3. request - This is same as prototype scope, however it’s meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.

4. session - A new bean will be created for each HTTP session by the container.

5. global-session - This is used to create global session beans for Portlet applications.

Spring Framework is extendable and we can create our own scopes too. However, most of the
times we are good with the scopes provided by the framework.
Spring Bean Configuration

Spring Framework provides three ways to configure beans to be used in the application.

1. Annotation Based Configuration - By using @Service or @Component annotations.


Scope details can be provided with @Scope annotation.

2. XML Based Configuration - By creating Spring Configuration XML file to configure the
beans. If you are using Spring MVC framework, the xml based configuration can be loaded
automatically by writing some boiler plate code in web.xml file.

3. Java Based Configuration - Starting from Spring 3.0, we can configure Spring beans using
java programs. Some important annotations used for java based configuration
are @Configuration, @ComponentScan and @Bean.

Spring IoC and Spring Bean Example Project


Let’s look at the different aspects of Spring IoC container and Spring Bean configurations with a
simple Spring project. For my example, I am creating a Spring MVC project in Spring Tool Suite. If
you are new to Spring Tool Suite and Spring MVC, please read Spring MVC Tutorial with Spring Tool
Suite.

The final project structure looks like below image. Let’s look at different components of Spring IoC
and Spring Bean project one by one.
XML Based Spring Bean Configuration

MyBean is a simple Java POJO class.

Spring Configuration XML File

servlet-context.xml code:
Notice that MyBean is configured using bean element with scope as singleton.

Annotation Based Spring Bean Configuration


MyAnnotatedBean is configured using @Service and scope is set to Request.

Spring IoC Controller Class

HomeController class will handle the HTTP requests for the home page of the application. We will
inject our Spring beans to this controller class through WebApplicationContext container.
Deployment Descriptor

We need to configure our application for Spring Framework so that the configuration metadata will
get loaded and context will be initialized.
Almost all the configuration above is boiler-plate code generated by STS tool automatically.

Run the Spring IoC Bean Example Application

Now when you will launch the web application, the home page will get loaded and in the console
following logs will be printed when you refresh the page multiple times.

MyBean hashcode=118267258

MyAnnotatedBean hashcode=1703899856

MyBean hashcode=118267258

MyAnnotatedBean hashcode=1115599742

MyBean hashcode=118267258

MyAnnotatedBean hashcode=516457106

Notice that MyBean is configured to be a singleton, so the container is always returning the same
instance and hashcode is always the same. Similarly, for each request, a new instance of
MyAnnotatedBean is created with different hashcode.

Java Based Spring Bean Configuration

For standalone applications, we can use annotation based as well as XML based configuration.
The only requirement is to initialize the context somewhere in the program before we use it.
The annotation based configuration class that will be used to initialize the Spring container.
A simple test program where we are initializing the AnnotationConfigApplicationContext context
and then using getBean() method to get the instance of MyService. Notice that I am calling
getBean method two times and printing the hashcode. Since there is no scope defined for
MyService, it should be a singleton and hence hashcode should be the same for both the
instances. When we run the above application, we get following console output confirming our
understanding.

Sat Dec 28 22:49:18 PST 2013::Hi

service hashcode=678984726
newService hashcode=678984726

If you are looking for XML based configuration, just create the Spring XML config file and then
initialize the context with following code snippet.

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(

"applicationContext.xml");

MyService app = context.getBean(MyService.class);

That’s all for the Spring IoC example tutorial, Spring Bean Scopes and Configuration details.
Download the Spring IoC and Spring Bean example project from below link and play around with it
for better understanding.

Spring Bean Scopes


There are five types of spring bean scopes:

1. singleton - only one instance of the spring bean will be created for the spring container.
This is the default spring bean scope. While using this scope, make sure bean doesn’t have
shared instance variables otherwise it might lead to data inconsistency issues.

2. prototype – A new instance will be created every time the bean is requested from the
spring container.

3. request – This is same as prototype scope, however it’s meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.

4. session – A new bean will be created for each HTTP session by the container.

5. global-session – This is used to create global session beans for Portlet applications.

Spring Bean Singleton and Prototype Scope

Spring bean singleton and prototype scopes can be used in standalone spring apps. Let’s see how
we can easily configure these scopes using @Scope annotation. Let’s say we have a java bean
class.
Let’s define the spring configuration class where we will define the method to get MyBean
instance from spring container.

Note that singleton is default scope, so we can remove @Scope(value="singleton") from above
bean definition. Now let’s create a main method and test the singleton scope.
When above program is executed, we will get output like below.

MyBean instance created

867988177

867988177

Notice that both MyBean instances have same hashcode and the constructor is called once once,
it means that spring container is returning the same instance of MyBean always. Now let’s change
the scope to prototype.

This time we will get following output when main method is executed.
It’s clear that MyBean instance is created every time it’s requested from spring container. Now
let’s change the scope to request.

In this case, we will get following exception.

Exception in thread "main" java.lang.IllegalStateException: No Scope registered for scope name


'request'

at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactor
y.java:347)

at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.j
ava:224)

at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(Def
aultListableBeanFactory.java:1015)

at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListable
BeanFactory.java:339)

at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListable
BeanFactory.java:334)

at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationC
ontext.java:1107)

at com.journaldev.spring.MySpringApp.main(MySpringApp.java:12)

It’s because request, session and global-session scopes are not available for standalone
applications.
Spring Bean Request and Session Scope
For spring bean request and session scope example, we will create Spring Boot web application.
Create a spring boot starter project and choose “web” so that we can run it as a web application.

Our final project will look like below


image.
ServletInitializer and SpringBootMvcApplication are auto generated spring boot classes. We don’t
need to make any changes there. Here is my pom.xml file, have a look at the dependencies for our
application. Your pom.xml file might be slightly different based on the Eclipse version you are
using.
Let’s create some spring components and configure them as spring beans in the spring container
with scope as request and session.

Spring Bean Request Scope


Spring Bean Session Scope
Spring Component
Now let’s create a spring component and use spring to auto configure above beans.
Spring Rest Controller
Finally, let’s create a RestController class and configure some API end points for our testing
purposes.
Spring Boot Session Timeout Configuration

Finally we have to configure spring boot session timeout variables, add below properties
in src/main/resources/application.properties.

server.session.cookie.max-age= 1

server.session.timeout= 1

Now our spring beans with session scope will be invalidated in one minute. Just run
the SpringBootMvcApplication class as spring boot application. You should see below output for
our endpoints being configured.

2018-05-23 17:02:25.830 INFO 6921 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping :


Mapped "{[/nameRS]}" onto public java.lang.String com.journaldev.spring.HelloData.helloRS()

2018-05-23 17:02:25.831 INFO 6921 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping :


Mapped "{[/nameSSUpdated]}" onto public java.lang.String
com.journaldev.spring.HelloData.helloSSUpdated()

2018-05-23 17:02:25.832 INFO 6921 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping :


Mapped "{[/nameSS]}" onto public java.lang.String com.journaldev.spring.HelloData.helloSS()

Spring Bean Request Scope Test

Open any browser and go to URL https://localhost:8080/nameRS and check the console output.
You should see DataRequestScope Constructor Called getting printed on each request.

Spring Bean Session Scope Test

Go to https://localhost:8080/nameSS and you would get following output.

Now go
to https://localhost:8080/nameSSUpdated so that DataSessionScope name value is updated
to Session Scope Updated.
Now again go to https://localhost:8080/nameSS and you should see the updated value.

By this time, you


should see DataSessionScope Constructor Called at XXX only once in the console output. Now
wait for 1 minute so that our session scoped bean is invalidated. Then again go
to https://localhost:8080/nameSS and you should see the original output. Also you should check
console message for creation of DataSessionScope again by the container.

That’s all for spring beans scope tutorial.

Spring @Autowired Annotation


Spring @Autowired annotation is used for automatic dependency injection. Spring framework is
built on dependency injection and we inject the class dependencies through spring bean
configuration file.
Usually we provide bean configuration details in the spring bean configuration file and we also
specify the beans that will be injected in other beans using ref attribute. But Spring framework
provides autowiring features too where we don’t need to provide bean injection details explicitly.
There are different ways through which we can autowire a spring bean.

1. autowire byName - For this type of autowiring, setter method is used for dependency
injection. Also the variable name should be same in the class where we will inject the
dependency and in the spring bean configuration file.

2. autowire byType - For this type of autowiring, class type is used. So there should be only
one bean configured for this type in the spring bean configuration file.

3. autowire by constructor - This is almost similar to autowire byType, the only difference is
that constructor is used to inject the dependency.

4. autowire by autodetect - If you are on Spring 3.0 or older versions, this is one of the
autowire options available. This option was used for autowire by constructor or byType, as
determined by Spring container. Since we already have so many options, this option is
deprecated. I will not cover this option in this tutorial.

5. @Autowired annotation - We can use Spring @Autowired annotation for spring bean
autowiring. @Autowired annotation can be applied on variables and methods for
autowiring byType. We can also use @Autowired annotation on constructor for constructor
based spring autowiring. For @Autowired annotation to work, we also need to enable
annotation based configuration in spring bean configuration file. This can be done
by context:annotation-config element or by defining a bean of
type org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProces
sor.

6. @Qualifier annotation - This annotation is used to avoid conflicts in bean mapping and we
need to provide the bean name that will be used for autowiring. This way we can avoid
issues where multiple beans are defined for same type. This annotation usually works with
the @Autowired annotation. For constructors with multiple arguments, we can use this
annotation with the argument names in the method.

By default spring bean autowiring is turned off. Spring bean autowire default value is “default” that
means no autowiring is to be performed. autowire value “no” also have the same behavior. To
showcase the use of Spring Bean autowiring, let’s create a simple Spring Maven project. Our final
project will look like below image.
Let’s look into each of the
autowire options one by one. For that we will create a Model bean and a service class where we
will inject the model bean.

Spring @Autowired Annotation - Maven Dependencies


For spring autowiring, we don’t need to add any additional dependencies. Our pom.xml file has
spring framework core dependencies and looks like below.
Spring @Autowired Annotation - Model Bean
Let’s create a simple Java Bean, named Employee. This bean will have a single property with getter
and setter methods. We will initialize this property value in the spring bean configuration file.
Spring @Autowired Annotation - Service Class

Let’s create our service class in which we will inject Employee bean through spring autowiring.
We will use the same service class for perform spring autowiring byName, byType and by
constructor. The setter method will be used for spring autowiring byName and byType whereas
constructor based injection will be used by constructor autowire attribute. When we use spring
autowire byName or byType, default constructor is used. That’s why we have explicitly defined the
default constructor for the EmployeeService bean.

Spring @Autowired Annotation - autowiring byType Example

Let’s create a separate class with Spring @Autowired annotation for autowiring byType.
Note that I have annotated both Employee variable and it’s setter method with
Spring @Autowired annotation, however only one of these is sufficient for spring bean autowiring.

Spring @Autowired Annotation and @Qualifier Bean autowiring by constructor


Example
Let’s create another service class where we will use @Autowired annotation for constructor based
injection. We will also see @Qualifier annotation usage.
When this bean will be initialized by Spring framework, bean with name as “employee” will be
used for autowiring. Spring @Autowired annotation excepts one argument “required” that is a
boolean with default value as TRUE. We can define it to be “false” so that spring framework don’t
throw any exception if no suitable bean is found for autowiring.

Spring @Autowired Annotation - Bean Configuration File


Spring bean configuration file is the main part of any spring application, let’s see how our spring
bean configuration file looks and then we will look into each part of it.
Important points about spring bean configuration file are:

• beans element default-autowire is used to define the default autowiring method. Here I am
defining the default autowiring method to be byName.

• beans element default-autowire-candidates is used to provide the pattern for bean names
that can be used for autowiring. For simplicity I am allowing all the bean definitions to be
eligible for autowiring, however if we can define some pattern for autowiring. For example,
if we want only DAO bean definitions for autowiring, we can specify it as default-autowire-
candidates="*DAO".

• autowire-candidate="false" is used in a bean definition to make it ineligible for autowiring.


It’s useful when we have multiple bean definitions for a single type and we want some of
them not to be autowired. For example, in above spring bean configurations “employee1”
bean will not be used for autowiring.

• autowire attribute byName, byType and constructor is self understood, nothing much to
explain there.

• context:annotation-config is used to enable annotation based configuration support.


Notice that employeeAutowiredByTypeService and
employeeAutowiredByConstructorService beans don’t have autowire attributes.

Spring @Autowired Annotation - Test Program


Now that our spring application is ready with all types of spring autowiring, let’s write a simple test
program to see if it works as expected or not.
The program is simple, we are just creating the spring application context and using it to get
different beans and printing the employee name. When we run above application, we get following
output.

Mar 31, 2014 10:41:58 PM org.springframework.context.support.ClassPathXmlApplicationContext


prepareRefresh

INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@3fa99295: startup date
[Mon Mar 31 22:41:58 PDT 2014]; root of context hierarchy
Mar 31, 2014 10:41:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [spring.xml]

Default Constructor used

Default Constructor used

Autowiring by constructor used

Autowiring byName. Employee Name=Pankaj

Autowiring byType. Employee Name=Pankaj

Autowiring by Constructor. Employee Name=Pankaj

21594592::15571401::1863015320

@Autowired byType. Employee Name=Pankaj

@Autowired by Constructor. Employee Name=Pankaj

Mar 31, 2014 10:41:58 PM org.springframework.context.support.ClassPathXmlApplicationContext


doClose

INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@3fa99295:


startup date [Mon Mar 31 22:41:58 PDT 2014]; root of context hierarchy

As you can see that for autowire byName and byType, default no-args constructor is used to
initialize the bean. For autowire by constructor, parameter based constructor is used. From the
hashcode of all the variables, we have confirmed that all the spring beans are different objects
and not referring to the same object. Since we removed “employee1” from the list of eligible beans
for autowiring, there was no confusion in the bean mapping. If we remove autowire-
candidate="false" from the “employee1” definition, we will get below error message when
executing the above main method.

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException:


Error creating bean with name 'employeeServiceByType' defined in class path resource
[spring.xml]: Unsatisfied dependency expressed through bean property 'employee': : No qualifying
bean of type [com.journaldev.spring.autowiring.model.Employee] is defined: expected single
matching bean but found 2: employee,employee1; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type
[com.journaldev.spring.autowiring.model.Employee] is defined: expected single matching bean
but found 2: employee,employee1
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByTyp
e(AbstractAutowireCapableBeanFactory.java:1278)

at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean
(AbstractAutowireCapableBeanFactory.java:1170)

at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
(AbstractAutowireCapableBeanFactory.java:537)

at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(A
bstractAutowireCapableBeanFactory.java:475)

at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFact
ory.java:304)

at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSi
ngletonBeanRegistry.java:228)

at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactor
y.java:300)

at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.j
ava:195)

at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons
(DefaultListableBeanFactory.java:700)

at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(
AbstractApplicationContext.java:760)

at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationCo
ntext.java:482)
at
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlAppli
cationContext.java:139)

at
org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlAppli
cationContext.java:83)

at com.journaldev.spring.autowiring.main.SpringMain.main(SpringMain.java:12)

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying


bean of type [com.journaldev.spring.autowiring.model.Employee] is defined: expected single
matching bean but found 2: employee,employee1

at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(
DefaultListableBeanFactory.java:967)

at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(Def
aultListableBeanFactory.java:855)

at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByTyp
e(AbstractAutowireCapableBeanFactory.java:1263)

... 13 more
Spring Bean Life Cycle
Today we will look into Spring Bean Life Cycle. Spring Beans are the most important part of any
Spring application. Spring ApplicationContext is responsible to initialize the Spring Beans defined
in spring bean configuration file.

Spring Bean Life Cycle

Spring Context is also responsible for injection dependencies in the bean, either through setter or
constructor methods or by spring autowiring. Sometimes we want to initialize resources in the
bean classes, for example creating database connections or validating third party services at the
time of initialization before any client request. Spring framework provide different ways through
which we can provide post-initialization and pre-destroy methods in a spring bean life cycle.

1. By implementing InitializingBean and DisposableBean interfaces - Both these interfaces


declare a single method where we can initialize/close resources in the bean. For post-
initialization, we can implement InitializingBean interface and provide implementation
of afterPropertiesSet() method. For pre-destroy, we can
implement DisposableBean interface and provide implementation of destroy() method.
These methods are the callback methods and similar to servlet listener implementations.
This approach is simple to use but it’s not recommended because it will create tight
coupling with the Spring framework in our bean implementations.

2. Providing init-method and destroy-method attribute values for the bean in the spring bean
configuration file. This is the recommended approach because of no direct dependency to
spring framework and we can create our own methods.

Note that both post-init and pre-destroy methods should have no arguments but they can throw
Exceptions. We would also require to get the bean instance from the spring application context for
these methods invocation.

Spring Bean Life Cycle - @PostConstruct, @PreDestroy Annotations


Spring framework also support @PostConstruct and @PreDestroy annotations for defining post-
init and pre-destroy methods. These annotations are part of javax.annotation package. However
for these annotations to work, we need to configure our spring application to look for annotations.
We can do this either by defining bean of
type org.springframework.context.annotation.CommonAnnotationBeanPostProcessor or
by context:annotation-config element in spring bean configuration file. Let’s write a simple Spring
application to showcase the use of above configurations for spring bean life cycle management.
Create a Spring Maven project in Spring Tool Suite, final project will look like below image.

Spring Bean Life Cycle - Maven Dependencies

We don’t need to include any extra dependencies for configuring spring bean life cycle methods,
our pom.xml file is like any other standard spring maven project.
Spring Bean Life Cycle - Model Class

Let’s create a simple java bean class that will be used in service classes.
Spring Bean Life Cycle - InitializingBean, DisposableBean

Let’s create a service class where we will implement both the interfaces for post-init and pre-
destroy methods.
Spring Bean Life Cycle - Custom post-init, pre-destroy
Since we don’t want our services to have direct spring framework dependency, let’s create another
form of Employee Service class where we will have post-init and pre-destroy spring life cycle
methods and we will configure them in the spring bean configuration file.
We will look into the spring bean configuration file in a bit. Before that let’s create another service
class that will use @PostConstruct and @PreDestroy annotations.

Spring Bean Life Cycle - @PostConstruct, @PreDestroy

Below is a simple class that will be configured as spring bean and for post-init and pre-destroy
methods, we are using @PostConstruct and @PreDestroy annotations.
Spring Bean Life Cycle - Configuration File

Let’s see how we will configure our beans in spring context file.
Notice that I am not initializing employee name in it’s bean definition. Since EmployeeService is
using interfaces, we don’t need any special configuration here. For MyEmployeeService bean, we
are using init-method and destroy-method attributes to let spring framework know our custom
methods to execute. MyService bean configuration doesn’t have anything special, but as you can
see that I am enabling annotation based configuration for this. Our application is ready, let’s write
a test program to see how different methods get executed.

Spring Bean Life Cycle - Test Program


When we run above test program, we get below output.

Apr 01, 2014 10:50:50 PM org.springframework.context.support.ClassPathXmlApplicationContext


prepareRefresh

INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@c1b9b03: startup date
[Tue Apr 01 22:50:50 PDT 2014]; root of context hierarchy

Apr 01, 2014 10:50:50 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader


loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [spring.xml]

EmployeeService no-args constructor called

EmployeeService initializing to dummy value

MyEmployeeService no-args constructor called

MyEmployeeService initializing to dummy value

MyService no-args constructor called

MyService init method called


Spring Context initialized

Bean retrieved from Spring Context

Employee Name=Pankaj

Apr 01, 2014 10:50:50 PM org.springframework.context.support.ClassPathXmlApplicationContext


doClose

INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@c1b9b03:


startup date [Tue Apr 01 22:50:50 PDT 2014]; root of context hierarchy

MyService destroy method called

MyEmployeeService Closing resources

EmployeeService Closing resources

Spring Context Closed

Spring Bean Life Cycle Important Points:


• From the console output it’s clear that Spring Context is first using no-args constructor to
initialize the bean object and then calling the post-init method.

• The order of bean initialization is same as it’s defined in the spring bean configuration file.

• The context is returned only when all the spring beans are initialized properly with post-init
method executions.

• Employee name is printed as “Pankaj” because it was initialized in the post-init method.

• When context is getting closed, beans are destroyed in the reverse order in which they were
initialized i.e in LIFO (Last-In-First-Out) order.

You can uncomment the code to get bean of type MyEmployeeService and confirm that output will
be similar and follow all the points mentioned above.

Spring Aware Interfaces


Sometimes we need Spring Framework objects in our beans to perform some operations, for
example reading ServletConfig and ServletContext parameters or to know the bean definitions
loaded by the ApplicationContext. That’s why spring framework provides a bunch of *Aware
interfaces that we can implement in our bean
classes. org.springframework.beans.factory.Aware is the root marker interface for all these Aware
interfaces. All of the *Aware interfaces are sub-interfaces of Aware and declare a single setter
method to be implemented by the bean. Then spring context uses setter-based dependency
injection to inject the corresponding objects in the bean and make it available for our use. Spring
Aware interfaces are similar to servlet listeners with callback methods and implementing observer
design pattern. Some of the important Aware interfaces are:

• ApplicationContextAware - to inject ApplicationContext object, example usage is to get


the array of bean definition names.

• BeanFactoryAware - to inject BeanFactory object, example usage is to check scope of a


bean.

• BeanNameAware - to know the bean name defined in the configuration file.

• ResourceLoaderAware - to inject ResourceLoader object, example usage is to get the


input stream for a file in the classpath.

• ServletContextAware - to inject ServletContext object in MVC application, example usage


is to read context parameters and attributes.

• ServletConfigAware - to inject ServletConfig object in MVC application, example usage is


to get servlet config parameters.

Let’s see these Aware interfaces usage in action by implementing few of them in a class that we
will configure as spring bean.
Spring *Aware Example Configuration File

Very simple spring bean configuration file.


Now when we execute above class, we get following output.

Apr 01, 2014 11:27:05 PM org.springframework.context.support.ClassPathXmlApplicationContext


prepareRefresh

INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@60a2f435: startup date
[Tue Apr 01 23:27:05 PDT 2014]; root of context hierarchy

Apr 01, 2014 11:27:05 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader


loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-aware.xml]

setBeanName called

setBeanName:: Bean Name defined in context=myAwareService

setBeanClassLoader called

setBeanClassLoader:: ClassLoader Name=sun.misc.Launcher$AppClassLoader

setBeanFactory called

setBeanFactory:: employee bean singleton=true

setEnvironment called

setResourceLoader called

setResourceLoader:: Resource File Name=spring.xml

setApplicationEventPublisher called

setApplicationContext called

setApplicationContext:: Bean Definition Names=[employee, myAwareService]

Apr 01, 2014 11:27:05 PM org.springframework.context.support.ClassPathXmlApplicationContext


doClose

INFO: Closing
org.springframework.context.support.ClassPathXmlApplicationContext@60a2f435: startup date
[Tue Apr 01 23:27:05 PDT 2014]; root of context hierarchy

Console output of the test program is simple to understand, I won’t go into much detail about that.
That’s all for the Spring Bean Life Cycle methods and injecting framework specific objects into the
spring beans.

Spring Annotations
1. Spring Annotations A brief look at the most important annotations in spring framework.

2. Spring @Bean Spring @Bean Annotation is applied on a method to specify that it returns a
bean to be managed by Spring context. Spring Bean annotation is usually declared in
Configuration classes methods.

3. Spring @Service Spring @Service annotation is a specialization


of @Component annotation. Spring Service annotation can be applied only to classes. It is
used to mark the class as a service provider.
4. Spring @Component Spring Component annotation is used to denote a class as
Component. It means that the Spring framework will autodetect these classes for
dependency injection when annotation-based configuration and classpath scanning is
used.

5. Spring @RestController Spring RestController annotation is a convenience annotation


that is itself annotated with @Controller and @ResponseBody. This annotation is applied
to a class to mark it as a request handler.

6. Spring @Controller Spring Controller annotation is a specialization


of @Component annotation. Spring Controller annotation is typically used in combination
with annotated handler methods based on the RequestMapping annotation.

7. Spring @Repository Spring @Repository annotation is used to indicate that the class
provides the mechanism for storage, retrieval, search, update and delete operation on
objects.

8. Spring @Configuration 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.

9. Spring @Value Spring @Value annotation is used to assign default values to variables and
method arguments. We can read spring environment variables as well as system variables
using @Value annotation.

10. Spring @PropertySource Spring @PropertySource annotation is used to provide


properties file to Spring Environment. This annotation is used with @Configuration classes.

11. Spring @PostConstruct and @PreDestroy When we annotate a method in Spring Bean
with @PostConstruct annotation, it gets executed after the spring bean is initialized. When
we annotate a Spring Bean method with PreDestroy annotation, it gets called when bean
instance is getting removed from the context.

12. Spring @Async Spring @Async annotation allows us to create asynchronous methods in
spring. Let’s explore @Async in this tutorial on spring framework.

Spring Boot Tutorials

1. Spring Boot Tutorial

2. Spring Boot Components


3. Spring Boot @SpringBootApplication, SpringApplication Class Spring
Boot @SpringBootApplication annotation is used to mark a configuration class that
declares one or more @Bean methods and also triggers auto-configuration and
component scanning. Spring Boot SpringApplication class is used to bootstrap and launch
a Spring application from a Java main method.

4. Spring Boot REST This tutorial explains how to create REST web services using the Spring
Boot module.

5. Spring Boot MongoDB Learn how to use MongoDB in a Spring Boot application.

6. Spring Boot Redis Cache This article explains how to integrate Redis Cache into a spring
boot application.

7. Spring Boot Elasticsearch This article explains how to integrate Elasticsearch with a
spring boot application.

8. Spring Boot Actuator Endpoints Spring Boot Actuator Endpoints lets us monitor and
interact with our application. Spring Actuator is a Spring Boot sub-module and provides
built-in endpoints that we can enable and disable for our application.

9. Spring Boot Initializr Web Interface

10. Spring Boot CLI Example

11. Spring Boot – Cannot determine embedded database driver class for database type
NONE

12. Spring Boot Interview Questions

You might also like