Spring Framework 4
Spring Framework 4
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.
Libraries are components that will contain the reusable code to address a problem
Architecture
(Libraries)
user Framework Jars
Application
Components Shaping an EE application
Enterprise Application
Requirement/Business
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
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
Singleton objects
Java based
If two classes depend closely on many details of each other, we say they
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
code
Coupling and Cohesion
Loose coupling makes it possible to:
Understand one class without reading others
Inversion of Control
The flow of dependencies in an application is managed by an externalized
Dependency Injection :
Dependency Injection or simply Spring DI is a Software Design Pattern
New
TextFileGenerator
() Class
TextFileGenerator
Loose coupling with Spring
Interface FileCreator
Class Class
OutPutHelper TextOutPutCr
eator
fileCreator Interface
fileGenerator FileGenerator
Class
TextFileGener
ator
pdfOutputGenerator
create a CSV
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 ;
}
}
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>
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
Instead of using <bean> tag in the xml, you can use @Component in the
@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”/>
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
Quartz 1.8.6
Minimum 2.1.4 as of Spring Framework 4.1,
Groovy
Groovy 1.8.6 as of Spring Framework 4.1,
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
@RestController
Public class EmployeeRestService {
@Autowired
private EmployeeService empService;
@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
The bean definition wired with this annotation will not be created when
@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.");
}
}
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
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String dbname = context.getEnvironment().getProperty("database.name");
return dbname.equalsIgnoreCase("prod");
}
@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
@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
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
ListenableFuture.get()
@Autowired
AsyncRestTemplate asyncRestTemplate;
in web applications
connected clients.
Structure
Spring – ApplicationContext.xml
Struts – Struts-config.xml
Hibernate – hibernate.cfg.xml
Behaviour
beans
Pre-defined infrastructure code
JdbcTemplate
DispatcherServlet
ApplicationContext
HandlerInterceptor/HandlerAdapter
Why Spring ?
Application composed of
Classes
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
Moduled
choices
Widely used
Support is abundant
In Spring,
Object creation is separate from application code
ApplicationContext
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
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
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,
using an application
Eg. Log information about all the functionalities that the user
After
@After - Advice the needs to be executed after the JoinPoint. This will
JoinPoint
After throwing
@AfterThrowing - Advice to be executed after an exception has been
@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 ? …
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.