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

Spring Framework 4

Spring framework

Uploaded by

Anilkasi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
364 views

Spring Framework 4

Spring framework

Uploaded by

Anilkasi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

Spring Framework

Enterprise Application

http://stackoverflow.com/questions/2190625/what-is-the-difference-
between-framework-and-architecture
Architecture
Architecture
consists of the
guiding principles
behind a given
application. It is
not strongly tied to
a particular
framework or
library
Framework
Framework is a part of
architecture implementation.

A Framework consists of one


or more libraries. The
application registers with the
framework (often by
implementing one or more
interfaces), and the framework
calls into the application, which
may call back into the
framework.

A framework often exists to


address a particular general-
purpose Domain (such as web
applications, or workflows,
etc.).
Framework & Library

Libraries are components that will contain the reusable code to address a problem

• Application is an organized set of instructions/commands based on architecture, and built


on top of a framework
• The framework makes the organizing easier, structured
• From the instructions of the framework, application executes picking help from libraries

Architecture
(Libraries)
user Framework Jars
Application
Components Shaping an EE application
 Enterprise Application
 Requirement/Business

 Architecture of the application (not bound to a framework)

 Technology

 Language
 Framework
 Libraries
 UI components
 Service Protocol (SOAP, REST)
 Design and Development
 Coding
 Classes and Objects

 Testing
 Maintenance
Components Shaping an EE application
 Classes are structure of the application
 They define how an object needs to be structured/created
 State via properties
 Behavior via methods

 Objects are the life givers to an application


 Multiple object collaborate to make a fully functioning system
 They interact based on the properties assigned
 The behavior is defined by the state of the object at a particular point
of time
 Eg. User -> {properties : username, password} -> doLogin(user)

 Login success

 Login failure
Components Shaping an EE application
 For an application to work successfully we need to take caution in,
 How the objects are created ?
 How they are organized/assembled ?
 How they are controlled ?
 How the memory is managed ?

 Developer problems
 From a developer point of view the coding for business + this infrastructure
work is tedious and time consuming
 Rewriting repeated code
 Debugging problems
 Confusions dealing with both technical infrastructure + business
 Spring
 Addresses the object creation/maintaining
 Common infrastructure via APIs, preventing boiler plate code
 Gives more time on addressing business
Enterprise Application
 It represents a business flow designed for a specific customer
 The requirements of the business are the key factors that build up
the architecture of the application
 Based on the architecture, a specific framework(s) is chosen
 Spring, Struts – for web related

 Oracle, MySQL – for database definitions

 Hibernate – for ORM related specifications

 Jquery, Angular js – For interactive UI

 CSS, HTML5, Bootstrap – For customizing look and feel

 XML, JSON – for data transfer standards

 SOAP, REST – for service related specifications


What Spring offers ?
 Inversion of control (IOC)
 Dependency Injection (DI)
 Annotations
 Spring container
 Application Context

 Singleton objects

 Make use of Plain POJO classes


 No specific style of coding required
Spring Framework
 The Spring Framework is a Java platform
 Provides comprehensive infrastructure support for developing
Java applications
 Spring handles the infrastructure. You focus on application
business
 Spring enables you to build applications from "plain old Java
objects" (POJOs)
 Make a Java method execute in a database transaction without having to deal
with Database/Transaction APIs.
 Make a local Java method a message handler without having to deal with JMS
APIs.
 Spring helps to have application code comprehensive by
separating dependencies from code logic
Spring Framework
 Spring also provides ways for organizing dependencies under a
container object
 The container can be created via
 XML definition

 Java based

 The container is the one which dispatches


Spring Framework
 Open Source application framework
 Addresses the complexity in EA development
 Layered architecture
 Can select on the components based on requirement

 Light weight Framework


What Software Engineering says?
 Coupling
 Coupling means dependency between classes

 If two classes depend closely on many details of each other, we say they

are tightly coupled.


 Cohesion
 Cohesion refers to the number and diversity of tasks that a class is

designed for.
 If a class is responsible for a few related logical tasks, we say it has high

cohesion.

 Code to interfaces
 Open/Close principles [1]
 Software entities (classes, modules, functions etc.) should be open for

extension, but closed for modification


 An entity can allow its behavior to be modified without altering its source

code
Coupling and Cohesion
 Loose coupling makes it possible to:
 Understand one class without reading others

 Change one class without affecting others

 Thus: improves maintainability

 High cohesion makes it easier to:


 Understand what a class or method does

 Use descriptive names

 Reuse classes or methods


Inversion Of Control (IOC) and Dependency Injection (DI)
 What is a Dependency ?
 Object collaborate to form the application functionality

 Thus the objects in an application have dependencies on each other

 Inversion of Control
 The flow of dependencies in an application is managed by an externalized

component/container and not the application by itself


 Moves object dependencies out of code

 Basically externalizing the dependencies

 It is a technique used to implement dependency injection in Spring

 Dependency Injection :
 Dependency Injection or simply Spring DI is a Software Design Pattern

that removes hard coded dependencies and make it possible to change


them at Compile time or Run Time.
 Spring Container implements this IOC + Dependency Injection design

pattern in Spring framework.


Tightly Coupled

• This class has 2 dependencies tightly coupled

Class TextOutPutHelper Class


TextOutPutCreator
New
TextOutPutCreato
r()

New
TextFileGenerator
() Class
TextFileGenerator
Loose coupling with Spring
Interface FileCreator
Class Class
OutPutHelper TextOutPutCr
eator
fileCreator Interface
fileGenerator FileGenerator

Class
TextFileGener
ator

This process is called


Dependency Injection Spring
Container
This is called, Inversion of Control
Problem behind Dependency Injection
public class TextOutputHelper
{
private TextOutputGenerator txtOutputGenerator;
public void setTextOutputGenerator txtOutputGenerator)
{
this. txtOutputGenerator = txtOutputGenerator;
}
}
 The problem - output always bounded to a text file
 High coupling – The bond between objects and classes
 Suppose if the object of this class is used in many places, and in case
the requirement changes from text file generation to pdf file
generation ?
 We need to manually change the output generator in every single class.
 Tedious to change, Rigid piece of code and will be prone to Errors
Dependency Injection
 Create an interface – like abstract defintion
interface IOutputGenerator
{
void generateOutputFile();
}

 Any no of generators can be written, implementing the interface


Dependency Injection
public class CsvOutputGenerator implements IOutputGenerator
{
public void generateOutputFile() {
// generate CSV file
}
}
public class JsonOutputGenerator implements IOutputGenerator
{
public void generateOutputFile() {
// generate JSON file
}
}
public class PdfOutputGenerator implements IOutputGenerator
{
public void generateOutputFile() {
// generate PDF file
}
}
Dependency Injection

pdfOutputGenerator

<bean id=“pdfOutputGenerator” class=“com.mkyong.output.impl.PdfOutputGenerator”/>

• Here there are 2 different generators.


• CsvOutputGenerator
• JsonOutputGenerator
• Ease in changing the output generator – Just define the bean and change in the xm
How Software engineering principles map to Spring
framework ?
 Provides high cohesive code
 CSV generator generates and contains logics about only how to

create a CSV

 Provides loose coupling


 Since we are using interfaces in place of classes, we can refer

to any output generator, just by assigning it to the interface and


not the actual classes

 Thus, the helper class can change to any type of outputGenerator


objects with minimal change, satisfying what open/closed principle
states.
The Language of Spring - Beans
 A Spring bean is nothing but an instance/object of a class
 Java way of creating a new object
OutputGenerator pdfOutputGenerator = new PdfOutputGenerator();
 Spring’s way of creating a bean (An object)
<bean id=“pdfOutputGenerator”
class=“com.mkyong.output.impl.PdfOutputGenerator”/>
 Any type of an object can be created via bean defintion
 Collection objects (List, Set, Map etc)
 Scopes of a Spring bean
 Singleton – All beans in spring a by default singleton
 Same instance is returned all the time
 Prototype
 A new object is returned every time invoked
 Request & Session
 Scoped with the validity of the Http Request / HttpSession (Only for WEB
application)
Why Spring beans are Singleton?
 Spring is a framework
 Most of the bean definitions we define in a context file is
configuration metadata
 Eg. Datasource, controllers, DAOs etc
 In OOPs an object’s behavior changes when its state changes
 State of an object is realized by its properties
 In such meta data configurations, the state of the object doesn’t
change.
 Their properties will remain constant for the lifetime of the
application
 The statefull information in an application is carried out by BO, VO,
or DTO objects, which are not annotated or not defined in the
spring context
Why Spring beans are Singleton?
 So, there is no need to maintain multiple instances of such meta-
data bean definitions. Hence, it is singleton
 It avoids concurrency issues, and gives the same information from
start to end of an application maintaining consistency
 Remember these singletons are not JVM singletons but Spring
container managed Singletons.
 JVM singleton – one instance per class loader
 Spring singleton – one instance per container, per bean

 http://java-sample-program.blogspot.in/2012/11/spring-singleton-
beans-vs-singleton.html
Creating beans - Examples
 Every object has properties and their corresponding
states
class CarDriving {
private boolean isStarted;
public void setIsStarted(boolean isStarted)
{
this. isStarted = isStarted ;
}
}

 CarDriving is the class


 isStarted is the property
 True or False is the state (the value of the property)
Creating beans - Examples
 In Spring, we initialize an object as a bean definition, along with its
properties and state, in special file called the “applicationContext.xml”
as follows

<bean id=“carDriving” class=“com.sample.CarDriving”> The class


<property name=“isStarted”> The Property
<value>true</value> The Value for the Property
</property>
</bean>

Shortcut :
<bean id=“carDriving” class=“com.sample.CarDriving”>
<property name=“isStarted” value=“true” type=“java.lang.boolean”/>
</bean>
Injecting beans
class CarDriving {
private Car car;
private boolean isStarted;
public void setCar(Car car) {
this. car = car;
}
public void setIsStarted(boolean isStarted) {
this. isStarted = isStarted ;
}
} <bean id=“carDriving” class=“com.sample.CarDriving”>
<property name=“car”>
<ref bean=“car”/>
</property>

Bean definition and Injection <property name=“isStarted”>


<value>true</value>
</property>
</bean>
<bean id=“car” class=“com.sample.Car”/>
How to access a bean from Spring container?
By Programmatic means :

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {


public static void main( String[] args ) {
ApplicationContext context = new ClassPathXmlApplicationContext(new
String[] {“applicationContext.xml"});
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
Dependency Injection - Types
 Setter Injection
Dependency Injection - Types
 Constructor Injection
Annotations
 Meta-data kind of abstractions, that instruct the complier to do a
certain operation
 @Component
 Makes a class eligible for bean definition

 Instead of using <bean> tag in the xml, you can use @Component in the

Java file itself


 Class/Type level annotation

 @Autowired
 Does the dependency injection part
 Takes a name or a type of the searches the Spring container for an
appropriate bean and injects it
 Field, method level annotation
Annotations - @Component
import org.springframework.stereotype.Component;

@Component
class CarDriving {
private boolean isStarted;
public void setIsStarted(boolean isStarted)
{
this. isStarted = isStarted ;
}
}
Is equal to
<bean id=“carDriving” class=“com.sample.CarDriving”>
Annotations - @Autowired
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
class CarDriving { <bean id=“carDriving” class=“com.sample.CarDriving”>
<property name=“car”>
@Autowired <ref bean=“car”/>
private Car car; </property>
Is equal to
private boolean isStarted;
<property name=“isStarted”>
<value>true</value>
public void setCar(Car car) { </property>
this. car = car; </bean>
} <bean id=“car” class=“com.sample.Car”/>

public void setIsStarted(boolean isStarted)


{
this. isStarted = isStarted ;
}
}
Spring Versions
Spring Version Support
 Spring 3.0.x and 3.1.x lines have been retired and no support
available anymore
 Spring 3.2.x is supported
 Limited support for 4.0.x versions are available
 The advice is to upgrade from 4.0.x to the most recent versions
like 4.1.x or 4.2.x
Spring 4 migration
 The min. versions to ensure while migrating to Spring 4 are
 JDK
 JDK 1.6 or above till 8

 J2EE components
 Servlet 3.0/J2EE 6

 Servers
 Tomcat 6.0.33 / 7.0.20 / 8.0.9
 Jetty 7.5
 JBoss AS 6.1 (note: JBoss EAP 6 recommended, since AS 6/7
community releases have many unresolved bugs)
 GlassFish 3.1 (note: deployment workaround necessary for non-
serializable session attributes)
 Oracle WebLogic 10.3.4 (with JPA 2.0 patch applied)
 IBM WebSphere 7.0.0.9 (with JPA 2.0 feature pack installed)
Spring 4 migration
 Frameworks
 JPA 2.0

 JMS 2.0

 JSF 2.0

 Jcache 1.0

 Bean validation 1.0


Spring 4 migration
 Libraries
 Hibernate Validator 4.3
 Hibernate ORM 3.6.10
 From Spring Framework 4.2, with Hibernate 4.2/4.3 recommended

 Apache Tiles 2.2.2


 Spring Framework 4.2, with Tiles 3.0.5 recommended

 Apache HttpComponents 4.3 (required for Spring's http.client package,


and for all of Spring as of 4.1.4)
 EhCache 2.4.7
 Minimum 2.5 as of Spring Framework 4.1,

 EhCache 2.8 or later recommended for Spring 4.2

 Quartz 1.8.6
 Minimum 2.1.4 as of Spring Framework 4.1,

 Quartz 2.2.1 recommended for Spring 4.2


Spring 4 migration
 Jackson
 Jackson 1.8.6 - Minimum 2.1 as of Spring Framework 4.1,

 Jackson 2.3 or later recommended for Spring 4.2

 Groovy
 Groovy 1.8.6 as of Spring Framework 4.1,

 Groovy 2.3 or later recommended for Spring 4.2

 Joda-Time 2.1 (note: 2.3 or later recommended)


 XStream 1.4
 Apache Velocity 1.7
 Apache POI 3.8
 JUnit 4.7 (note: minimum 4.9 as of Spring Framework 4.1, with JUnit
4.11 or later recommended)

 For more information :


 https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-
versions-of-the-spring-framework
Spring 4 Changes
 Removed Deprecated Packages and Methods
 API Differences Report

 Generic types qualifiers eligible for autowiring


@Autowired
Repository<Customer> customerRepository;

This is a Spring data repository bean definition. Introduced to


remove bolier plate coding to handle basic communications
with the DAO layers when using Persistence related API’s like
Hibernate.

http://docs.spring.io/spring-data/data-
commons/docs/1.6.1.RELEASE/reference/html/repositories.html
Spring 4 Changes - RestController
 @RestController
 Annotate any controller with this and you need not add @ResponseBody to the

methods returning data


 Specific for Restful services written in Spring

@RestController
Public class EmployeeRestService {

@Autowired
private EmployeeService empService;

public List<Employee> getEmployees(){


return empService.getAllEmployees();
}
}
Spring 4 Changes - RestController
 Before @RestController the same would have been like this

@Controller
Public class EmployeeRestService {

@Autowired
private EmployeeService empService;

@ResponseBody
public List<Employee> getEmployees(){
return empService.getAllEmployees();
}
}
Spring 4 changes – Meta-Annotations Support
 Meta-Annotation Support
 A meta-annotation is simply an annotation that can be applied to

another annotation.
 Example

 @Service in place of @Component

 Both are treated same by the Spring container

 Just that @Service, adds more meaning in terms of the context

of where it is added. Especially in the Service implementation


classes
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // Spring will see this and treat @Service in the same way as @Component
public @interface Service {
}
Spring 4 changes – Meta-Annotations Support
 Similarly, @RestController is a combination of
 @Controller and @ResponseBody annotations

 In this way you can combine two annotations to form a meaningful


annotation based on the requirment
Spring 4 features - @Lazy annotation
 @Lazy annotation
 Used along with @Configuration annotation

 The bean definition wired with this annotation will not be created when

the context is loaded


 These will be created only when the application needs them

 Till that these bean definitions will not be created

@Configuration
public class AppConf {
@Bean
@Lazy(value = true)
public A a(){
return new A();
}
@Bean
public B b(){
return new B();
}
}
public class A {
public A(){
System.out.println("class A initialized.");
}
}

public class B {
public B(){
System.out.println("class B initialized.");
}
}

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

//Class B will be initialized


ctx.register(AppConf.class);
ctx.refresh();

//Class A will be initialized


ctx.getBean(A.class);
Spring 4 features - @Description annotation
 @Description annotation
 Used to provide textual information on a bean

 Like Javadoc

@Configuration
public class AppConfig {

@Bean
@Description("Provides new instance of the Employee class")
public Employee createEmployee() {
return new Employee();
}

}
Spring 4 features - @Conditional annotation
 @Conditional annotation
 It is used to enable or disable a complete @Configuration class

 Even individual @Bean methods can be conditionally set

 The @Conditional annotation is consulted before the bean

definitions are created


 Example scenario

 We use different configurations for LOCAL, DEV, QA, PROD

 We can conditionally activate only the DEV related

configuration files pointed to DEV environment


 Depends on an interface Condition

 Need to implement the following method

public boolean matches(ConditionContext context, AnnotatedTypeMetadata


metadata)
Spring 4 features - @Conditional annotation
public class ProdDataSourceCondition implements Condition {

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String dbname = context.getEnvironment().getProperty("database.name");
return dbname.equalsIgnoreCase("prod");
}

public class DevDataSourceCondition implements Condition {

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String dbname = context.getEnvironment().getProperty("database.name");
return dbname.equalsIgnoreCase(“dev");
}

}
Spring 4 features - @Conditional annotation
@Configuration
public class EmployeeDataSourceConfig {

@Bean(name="dataSource")
@Conditional(value=DevDataSourceCondition.class)
public DataSource getDevDataSource() {
return new DevDatabaseUtil();
}

@Bean(name="dataSource")
@Conditional(ProdDataSourceCondition.class)
public DataSource getProdDataSource() {
return new ProductionDatabaseUtil();
}
}
Spring 4 features - @Import annotation
 @Import annotation
 Used to import multiple @Configuration classes into one master

configuration class
@Configuration
@Import({DataSourceConfig.class , WebAppConfig.class })
@Configuration public class AppConfig {
public class DataSourceConfig {
@Bean }
public DataSource dataSource() {
return new DriverManagerDataSource(...);
}
}

@Configuration
public class WebAppConfig {
@Bean
public ViewResolverRegistry viewRegistry() {
return new ViewResolverRegistry (...);
}
}
Spring 4 features - @ImportResource annotation
 @ImportResource Annotation
 It is possible to have bean definitions in

 XML and

 Java Configs

 The @ImportResource can be used to load a xml spring config file on to a

@Configuration class

@Configuration
@ImportResource("classpath:/com/bosch/config/spring-config.xml")
public class AppConfig {

@Bean
public DataSource dataSource() {
return new DriverManagerDataSource(url, username, password);
}
}
Spring 4 features - AsyncRestTemplate
 AsyncRestTemplate accesses the REST URL and return the
output asynchronously
 In synchronous HTTP processing, the code execution is blocked
until the response is fully received
 In async mode, the server process the response in a separate
thread and the code execution will continue
 Eg Listening to a message queue

 Listen for messages

 As and when the message reaches the handler, start

processing the message in different thread


 And the handler gets back to listening for messages

immediately
Spring 4 features - AsyncRestTemplate
 The return value of the AsyncRestTemplate is
 org.springframework.util.concurrent.ListenableFuture

 ListenableFuture object
 It waits for the result to be processed

 Once response is generated, we can get the result using

ListenableFuture.get()
@Autowired
AsyncRestTemplate asyncRestTemplate;

HttpHeaders headers = new HttpHeaders();


headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> requestEntity = new HttpEntity<String>("params", headers);

ListenableFuture<ResponseEntity<User>> future = asyncRestTemplate.exchange(url,


HttpMethod.GET, requestEntity, User.class);
try {
//waits for the result
ResponseEntity<String> entity = future.get();

//prints body source code for the given URL


System.out.println(entity.getBody());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Spring 4 features - others
 Spring web socket module
 WebSocket-based, two-way communication between client and server

in web applications

 Spring messaging module


 Support for STOMP as the WebSocket sub-protocol

 A programming model for routing and processing STOMP messages

from WebSocket clients


 As a result an @Controller can now contain both

 @RequestMapping methods for handling HTTP requests

 @MessageMapping methods for messages from WebSocket-

connected clients.

 Improvements in Spring testing framework


References
 Spring Basics
 http://www.mkyong.com/tutorials/spring-tutorials/
 http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/
 http://javapapers.com/spring/spring-conditional-annotation/
 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/
 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html
 Spring Interview Questions
 http://crackaninterview.com/spring-interview-questions/
 Software Engineering
 http://www.oodesign.com/design-principles.html
 http://en.wikipedia.org/wiki/Coupling_(computer_programming)
 http://www.xyzws.com/scjp/SGS11/5/2
 http://www.xyzws.com/scjp/SGS11/5/2
Spring Core
Spring Introduction
 Spring
 A Framework

 Structure

 Spring – ApplicationContext.xml

 Struts – Struts-config.xml

 Hibernate – hibernate.cfg.xml

 Behaviour

 Starts from applicationContext, dispatches/manages

beans
 Pre-defined infrastructure code

 JdbcTemplate

 DispatcherServlet

 ApplicationContext

 HandlerInterceptor/HandlerAdapter
Why Spring ?
 Application composed of
 Classes

 Objects and Methods

 Flow of data between objects and user/system events

 Objects are life of an application


 How they collaborate makes/breaks the application

 Manually managing objects (creation, maintenance, destroying)

is tedious and not part of actual business of the application


 Too much objects, the difficult its to maintain code

 Tightly coupled – objects are bound to the application

 Confusion, Tedious while changes, Effort wastage

 Less cohesion – A class does unwanted stuff than, its

intention
 Eg. Business class doing memory management

operations
Why Spring ?
 Spring addresses
 Tight coupling problem via Inversion of control and Dependency

Injection
 Less cohesion via, its predefined infrastructure code, so that we

can concentrate more on business logic than handling technical


 Light-weight

 Moduled

 Spring Core, Spring JDBC, Spring MVC

 No need to be bounded with all at once. Flexibility in the

choices
 Widely used

 Support is abundant

 Newly evolving and Supportive for Java

 Spring Data Rest, Spring 4 supports Java 8


Inversion of Control (IOC)
 Moving the object dependencies out of code
 The flow of objects is from container to application

 In Normal java code


 Application code + object dependencies are together

 In J2EE/Servlet based code,


 Servlet container manages the objects

 But cannot inject dependencies

 In Spring,
 Object creation is separate from application code

 Beans are defined in applicationContext.xml which in turn

becomes, a BeanFactory (Container)


Dependency Injection
 Injecting the dependencies to application code at runtime
 This is done by the Spring container, (BeanFactory)

 Useful when changes are made to application code


 Changes can be done in configuration file only rather than to make
modifications in many classes
Spring Container
 Contains all the object dependencies
 In Spring objects are termed as beans

 The general rule is to define all such dependency beans in an .xml


or a Java Configuration file
 When Spring boots up, this file will be fetched and processed first
 This in turn creates all the bean definitions/objects for the
application
 All bean definitions are stored in a special java class called as,
BeanFactory
 Based on the request/configuration, the beans/objects are injected
from BeanFactory to application code
Spring Container
 Two implementation for Spring Container are available
 BeanFactory

 ApplicationContext

 General work of a BeanFactory is,


 Load the bean definitions

 Create the beans

 Dispatch beans upon request

 Manage their life cycle


Spring Beans
 A Spring bean is basically an object
 Managed by a Spring container

 Bean Creation
 XML way

 Annotation way
Bean Life Cycle

BeanFactory
BeanFactoryPostProcessor
BeanPostProcessor
InitializingBean
DisposableBean
How to create a Spring Bean ?
 XML – Old way
 Annotations
 @Bean – Used in Java based application context configuration

 @Component – Any class annotated with this annotation is

eligible candidate for a spring bean.


 @Controller – Special type of @Component, specific for

handling Web requests (HTTP requests, responses)


 @Service – Same as component. Just a meaningful context to

use in the service classes. Meant for Service layer classes.


 @Repository – Same as component. Meant for DAO layer

classes. Converts SQL exceptions to DataAccessException


 You need to mention in the application context, where spring

can find the files annotated with @Component


Spring Bean Scope
 The are 5 different bean scopes in Spring
 Singleton

 Prototype

 Request

 Session

 Application
Why Spring beans are Singleton?
 Spring is a framework
 Most of the bean definitions we define in a context file is
configuration metadata
 Eg. Datasource, controllers, DAOs etc
 In OOPs an object’s behavior changes when its state changes
 State of an object is realized by its properties
 In such meta data configurations, the state of the object doesn’t
change.
 Their properties will remain constant for the lifetime of the
application
 The stateful information in an application is carried out by BO, VO,
or DTO objects, which are not annotated or not defined in the
spring context
Why Spring beans are Singleton?
 So, there is no need to maintain multiple instances of such meta-
data bean definitions. Hence, it is singleton
 It avoids concurrency issues, and gives the same information from
start to end of an application maintaining consistency
 Remember these singletons are not JVM singletons but Spring
container managed Singletons.
 JVM singleton – one instance per class loader
 Spring singleton – one instance per container, per bean

 http://java-sample-program.blogspot.in/2012/11/spring-singleton-
beans-vs-singleton.html
BeanFactoryPostProcessor class
 Called before the bean factory instance is created
 If any operation need to be completed before the BeanFactory
object is required, this can be used
 Part of container life cycle

 Example.
InitializingBean, DisposableBean interfaces
 They are interfaces which can be implemented on a bean

 InitializingBean interface
 org.springframework.beans.factory.InitializingBean
 Has one method, afterPropertiesSet()
 Called after the bean is created but before it is ready to be dispatched

 DisposableBean interface
 org.springframework.beans.factory.DisposableBean
 Has one method, destroy()
 Called when the bean is about to be destroyed (usually when the
container is closed)
InitializingBean, DisposableBean interfaces
Init and Destroy methods
 Its possible to have the same functionality without implementing
InitializingBean and DisposableBean
 Its via specifying init-method and destroy-method attributes on a
bean definition

<bean
id="beanPostProcessorBean"
class="com.test.xmlconfig.BeanPostProcessorDemo"
init-method="start"
destroy-method="end“/>
Init and Destroy methods
BeanPostProcessor Interface
 More control over object creation
 Provides 2 methods
BeanPostProcessor Interface
 Spring has many BeanPostProcessors defined within

Eg.
AutowiredAnnotationBeanPostProcessor
Autowires annotated fields, setter methods in the code

BeanValidationPostProcessor
Checks for JSR – 303 annotated Spring managed beans and
validated according to the properties assigned

http://stackoverflow.com/questions/29743320/how-exactly-works-the-
spring-bean-post-processor
Autowiring
 Autowiring does the actual dependency injection
 It can be done via
 Xml

 Annotation
Autowiring Types
 ByType
 Only one instance of a specific class can exist in the spring

container
Autowiring Types
 ByName
 More than one instance of a specific bean can be a business

demand
 We can have such beans with different name to be present in

the Spring container


 When marked as byName, spring will look for the bean name

rather than the type of the bean while autowiring


Autowiring
 The other 3 types are
 No – We have to explicitly do the autowiring

 Constructor – Same as byType but applied on contructors

 Autodetect – First tries constructor, if it doesn’t work tries

autowiring byType
Spring AOP
 Aspect Oriented Programming
 Adding extra functionality to your code by means of cross cutting
concerns
 These cross cutting concerns are called as Aspects

Aspects
 They are nothing but Java classes annotated with @Aspect

annotation
 An Aspect will contains the following

 Advices

 JoinPoints

 PointCuts
Spring AOP
 In the Aspects the developer can define, features like
 Logging,

 Transaction management(Commit, Rollback)

 Security Validation (Cleaning/Verifying input parameters)

 Serializing/Deserializing of input/output objects

 These features can be part of application code itself


 But the problem is the application code will become messy
 Lots of Logs than the code 

 Unnecessary code than the business will lead to confusion

 Difficulty in understanding/Maintainence of the application

 Using AOP the developer can externalize these functionalities and


use them if needed
Spring AOP
 How AOP works ?
 Say we need to log each and every move of the user while

using an application
 Eg. Log information about all the functionalities that the user

is using in the application


 If we add LOGs for each method then,

 The application code becomes clumsy

 The class is bounded to do more than that of the actual

business. Less Cohesive code.


 Here we can implement AOP

 Define Aspect class

 Define Advice methods

 Define Pointcuts to activate, the Advices when the

corresponding method execution is called


Spring AOP components
 ASPECT - Aspect is a program that cuts across multiple classes,
providing some additional functionality like logging, transaction mgmt,
checks etc.
 JOINPOINT - A JoinPoint represents a method execution. In general, it is
a point of execution, either a method execution/handling exception
 POINTCUT - A PointCut is like a URL to a JoinPoint. They are
expressions that points to the execution of the method
 ADVICE - An Advice, is nothing but an action, that needs to be performed
when a JoinPoint execution happens. Say, Logging method parameters,
Committing/Rollback
 TARGET OBJECT - The object on which the aspect is applied
 AOP PROXY - An object created by AOP proxy framework, in order to
implement the advices mentioned in the aspects
Spring AOP - Types of Advices
 Before
 @Before - Advice that needs to be executed before the JoinPoint

 After
 @After - Advice the needs to be executed after the JoinPoint. This will

be executed for both cases of Success/Error flow.


 After returning
 @AfterReturning - Advice to be executed after a normal flow of the

JoinPoint
 After throwing
 @AfterThrowing - Advice to be executed after an exception has been

thrown by the JoinPoint execution


 Around
 @Around - Advice to be executed, around the JoinPoint execution.

Covers Before and After


Spring AOP – Defining PointCuts
 A pointcut expression starts with a PointCutDesignator
 @PointCut("execution (public void
com.learn.spring.annotation.writer.ReportGenerator.generateRep
ort(String))")

 A pointcut will comprise of the following


 PointcutDesignator
 Return type of the method
 A fully qualified name for the package/class/method that’s being adviced
 Type of the arguments to the advised method

 A more generic way of defining is


 @PointCut("execution (* (com.learn.spring.annotation.writer.ReportGenerator.* (..))")
 @PointCut("execution (* (com.learn.spring.annotation.writer.ReportGenerator.* (..))")
 @PointCut("within(com.learn.spring.annotation.writer.*)")
Spring AOP How AOP works ? …
 When the user clicks on a button, it is likely to call a method
invocation in the application code. Say. Login
 Our Aspect has Advice methods, that will be executed when the
login method is called.
 The Aspect will get to know that the execution is happening via the
defined PointCut expressions

@Aspect
Class AppAspect
{
@Before("execution( com.learn.spring.UserLogin.(..))")
public void logBeforeLogin(JoinPoint joinPoint)
{
System.out.println(“User Login Aspect called before : " + joinPoint.getSignature().getName());
}
}
Spring AOP How AOP works ? …

AOP Proxy Object User Login

1. This whole process is called Aspect-Weaving


2. Weaving : A process of linking aspect with application code, to create an advised object
Spring AOP How AOP works ? …
 On loading the UserLogin class, spring identifies that there is an
aspect is defined
 Target class – UserLogin

 AOP class - AppAspect

 Spring creates a proxy object


 If the class has implemented any interface then a JDK proxy

object will be created


 If the class doesn’t implement any interface then a CGLIB proxy

object will be created


 The additional functionality is injected into the UserLogin,
 Then the flow of execution will be
 Log the user credentials (From Aspect)

 Invoke the actual login method (From App code)


Spring Modules (few)
Module When to use ?
Spring core • Core utilities used by other modules.
• Define this if you use Spring Utility APIs
(org.springframework.core./org.springframework.
util.)
Spring-expression • Expression Language
• Depends on spring-core
• Define this if you use Spring Expression APIs
(org.springframework.expression.)
Spring-beans • Bean Factory and JavaBeans utilities
• Depends on spring-core
• Define this if you use Spring Bean APIs
(org.springframework.beans.)
Spring-aop • Aspect Oriented Programming (AOP) Framework
• Depends on spring-core, spring-beans
• Define this if you use Spring AOP APIs
(org.springframework.aop.)
Spring Modules (few)
Module When to use ?
Spring-context • Application Context
• Depends on spring-core, spring-expression,
spring-aop, spring-beans
• This is the central artifact for Spring's
Dependency Injection Container and is generally
always defined
Spring-context-support • Various Application Context utilities, including
EhCache, JavaMail, Quartz, and Freemarker
integration
• Define this if you need any of these integrations
Spring-jdbc • JDBC Data Access Library
• Depends on spring-core, spring-beans, spring-
context, spring-tx
• Define this if you use Spring's JdbcTemplate API
(org.springframework.jdbc.)
Spring Modules (few)
Module When to use ?
Spring-tx • Transaction Management Abstraction
• Depends on spring-core, spring-beans, spring-
aop, spring-context
• Define this if you use Spring Transactions or
DAO Exception Hierarchy
• org.springframework.transaction./org.springframe
work.dao.
Spring-orm • Object-to-Relation-Mapping (ORM) integration
with Hibernate, JPA, and iBatis.
• Depends on spring-core, spring-beans, spring-
context, spring-tx
• Define this if you need ORM
org.springframework.orm.
Spring-test • Support for testing Spring applications with tools
such as JUnit and TestNG
Spring Modules (few)
Module When to use ?
Spring-oxm • Object-to-XML Mapping (OXM) abstraction and
integration with JAXB, JiBX, Castor, XStream,
and XML Beans.
• Depends on spring-core, spring-beans, spring-
context
• Define this if you need OXM
org.springframework.oxm.
Spring-web • Web application development utilities applicable
to both Servlet and Portlet Environments
• Depends on spring-core, spring-beans, spring-
context
• Define this if you use Spring MVC, or wish to use
Struts, JSF, or another web framework with
Spring (org.springframework.web.)
Spring-webmvc • Spring MVC for Servlet Environments
• Depends on spring-core, spring-beans, spring-
context, spring-web
• Define this if you use Spring MVC with a Servlet
Container such as Apache Tomcat
(org.springframework.web.servlet.)
THANK YOU

100 Internal | RBEI | 10/02/2014 | © Robert Bosch Engineering and Business Solutions Limited 2012. All rights reserved, also regarding
any disposal, exploitation, reproduction, editing, distribution, as well as in the event of applications for industrial property rights.

You might also like