FPT APTECH COMPUTER EDUCATION HANOI
Spring Framework
2
3
Dependency Injection and Inversion of Control
4
Bean scopes
• singleton(Default) Scopes a single bean definition to a single object instance per Spring IoC container.
• prototypeScopes a single bean definition to any number of object instances.
• requestScopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request
has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
• sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a
web-aware SpringApplicationContext.
• global sessionScopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when
used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
• custom scope To integrate your custom scope(s) into the Spring container, you need to implement
the org.springframework.beans.factory.config.Scope interface
6
Overview
7
Modules
Constructor-based dependency injection
• Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments
public class SimpleMovieLister { // the SimpleMovieLister has a dependency on a MovieFinder
private MovieFinder movieFinder; // a constructor so that the Spring container can 'inject' a MovieFinder
public SimpleMovieLister(MovieFinder movieFinder) { this.movieFinder = movieFinder; }
}
<bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”> <constructor-arg name=“movieFinder”><ref bean=“movieFinder”/></bean><bean id=“movieFinder” class=“example. MovieFinder”>
Setter-based dependency injection
• Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argumentstatic factory method to instantiate your bean.
public class SimpleMovieLister {
// the SimpleMovieLister has a dependency on a MovieFinder private MovieFinder movieFinder;
public SimpleMovieLister() { }
// a setter method so that the Spring container can 'inject' a MovieFinder public setMovieFinder (MovieFinder movieFinder) { this.movieFinder = movieFinder; } }
<bean id=“simpleMovieLister ” class=“example. SimpleMovieLister ”> <property name=“movieFinder”><ref bean=“movieFinder”/> </property></bean><bean id=“movieFinder” class=“example. MovieFinder”>
Abstract Beans
• Allows definition of part of a bean which can be reused many times in other bean definitions
The parent bean defines 2 values (name, age)
The child bean uses the parent age value (31)
The child bean overrides the parent name value (from parent-AZ to child-AZ)
Parent bean could not be injected, child could
<bean id="abstractBean" abstract="true“ class="org.example.ParentBean"> <property name="name" value="parent-AZ"/> <property name="age" value="31"/> </bean>
<bean id="childBean" class="org.example.ChildBean" parent="abstractBean" init-method="init">
<property name="name" value="child-AZ"/></bean>
The singleton scope
• The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans.
• The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.
<bean id="accountService" class=“DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default) --> <bean id="accountService" class=“DefaultAccountService" scope="singleton“/>
The prototype scope
• The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans.
• The following diagram illustrates the Spring prototype scope. A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.
<bean id="accountService" class=“DefaultAccountService" scope="prototype“/>
Request, session, and global session scopes
• Request scope
The Spring container creates a new instance of the LoginAction bean by using the loginAction bean definition for each and every HTTP request. That is, the loginAction bean is scoped at the HTTP request level. You can change the internal state of the instance that is created as much as you want, because other instances created from the same loginAction bean definition will not see these changes in state; they are particular to an individual request. When the request completes processing, the bean that is scoped to the request is discarded.
• Session scope
The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean definition for the lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at the HTTP Session level. As with request-scoped beans, you can change the internal state of the instance that is created as much as you want, knowing that other HTTP Session instances that are also using instances created from the same userPreferences bean definition do not see these changes in state, because they are particular to an individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded.
• Global session scope
The global session scope is similar to the standard HTTP Session scope and applies only in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared among all portlets that make up a single portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session.
<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session“/>
<bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession”/>
14
The Spring IOC Container
BeanFactory
15
Container Instantiation
Instantiating a Spring IoC container is easy;• Resource resource = new FileSystemResource("beans.xml");
– BeanFactory factory = new XmlBeanFactory(resource);• ClassPathResource resource = new
ClassPathResource("beans.xml");– BeanFactory factory = new XmlBeanFactory(resource);
• ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-part2.xml"});
// of course, an ApplicationContext is just a BeanFactory– BeanFactory factory = (BeanFactory) context;
16
Demo
17
Spring AOP
We believe that Aspect-Oriented Programming (AOP) offers a better solution to many problems than do existing technologies such as EJB. The AOP Alliance aims to ensure interoperability between Java/J2EE AOP implementations to build a larger AOP community.
AOP Alliance(http://aopalliance.sourceforge.net/)
19
Proxy pattern
DEAE / Session 9
20
Decorator pattern
DEAE / Session 9
21
AOP Fundamentals
• Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns– Transaction management– Security– Logging– Auditing– Locking
22
AOP concepts
• Aspect: a modularization of a concern that cuts across multiple classes
• Join point: a point during the execution of a program• Advice: action taken by an aspect at a particular join point• Pointcut: a predicate that matches join points• Introduction: declaring additional methods or fields on behalf
of a type: • Target object: object being advised by one or more aspects• AOP proxy: an object created by the AOP framework in order
to implement the aspect contracts• Weaving: linking aspects with other application types or
objects to create an advised object
23
Types of advice
• Before advice• After returning advice• After throwing advice• After (finally) advice• Around advice
DEAE / Session 9
24
AOP Proxies
• Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies
• Spring AOP can also use CGLIB proxies
DEAE / Session 9
25
@AspectJ support
• @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations
• Support configuration with XML
DEAE / Session 9
26
Declaring a pointcut
• execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP
• within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
• this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type
• target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type
• args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types
27
Declaring a pointcut
Examples
Declaring Pointcut & Advice
• Declaring A Pointcut
• Declaring advice
<aop:config> <aop:advisor pointcut=“SystemArchitecture.businessService()" advice-ref="tx-advice"/> </aop:config>
<tx:advice id="tx-advice"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice>Or@Pointcut("execution(* com.xyz.someapp.service.*.*(..))") public void businessService() {}
@Aspect public class AroundExample { @Around("com.xyz.myapp.SystemArchitecture.businessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.proceed(); // stop stopwatch return retVal; }
29
Demo