SlideShare a Scribd company logo
1 of 380
Download to read offline
1
Ramkrishna IT Systems
Vivek S. Kulkarni
Ramkrishna IT Systems
2
Ramkrishna IT Systems
• Understand the architecture of Spring
Framework
• Understand Dependency Injection
• AOP
• Develop sample applications using
– Spring AOP
– Spring JDBC Support
– Spring Hibernate integration
– Transactional Support in Spring
– Spring Remoting
– Spring MVC
3
Ramkrishna IT Systems
• Installing and Using STS
• Writing a simple Spring app
• Understanding ApplicationContext
• Learn bean lifecycle
• Learning Dependency Injection
– Constructor injection
– Setter Injection
• Annotation based DI
4
Ramkrishna IT Systems
Course Agenda: Day 2
•
•
•
•
•
AOP : Advice, JoinPoints, PointCuts and Aspects
Adding behavior to an application using aspects
Introducing data access with Spring
Simplifying JDBC-based data access
Driving database transactions in a Spring
environment
5
Ramkrishna IT Systems
Course Agenda: Day 3
• Introducing object-to-relational mapping (ORM)
• Getting started with Hibernate in a Spring
environment
• Web application architecture
• Getting started with Spring MVC
• Spring Remoting
6
Ramkrishna IT Systems
Overview of the Spring
Framework
Introducing Spring in the context of enterprise
application architecture
7
Ramkrishna IT Systems
What is Spring ?
A light-weight dependency injection and aspect-
oriented container and framework
8
Ramkrishna IT Systems
What is Spring ?
Light-Weight : Processing overhead required by spring is
negligible
Non-intrusive : Spring enabled application may not have
any dependency on spring, They can be run inside or outside
of the spring framework without any change in source code.
Dependency Injection : Promotes program-to-interface
design principle, thus promotes loose coupling. This technique
is reverse of JNDI –i.e. you do not look-up for dependant
objects in your code, container figures out required objects
and creates them and INJECTS them.
9
Ramkrishna IT Systems
What is Spring ?
Aspect-oriented : Application programmers do not write
logic for cross-cutting concerns such as logging, transaction,
security. The Spring framework provides the support for AOP.
Container : Spring is a container in the sense that it contains
and manages the lifecycle and configuration of application
objects. The association of different application objects, their
dependencies, their initialization etc. is configured and
container does the rest.
Framework : A large number of pre-defined classes and
interfaces provide a host of functionality required like
transaction management, MVC, integration with persistence
frameworks and so on. You write only business logic.
10
Ramkrishna IT Systems
Goal of the Spring
Framework
• Provide comprehensive infrastructural support
for developing enterprise Java™ applications
– Spring deals with the plumbing
– So you can focus on solving the domain problem
11
Ramkrishna IT Systems
Spring’s Support (1)
• Core support
Application Configuration
Enterprise Integration
Data Access
12
Ramkrishna IT Systems
Application Configuration
• A typical application system consists of several
parts working together to carry out a use case
Component A Component B
Component C
13
Ramkrishna IT Systems
A Typical Use Case
Spring Introduction
transfer(
“300.00”,
“1”, “2”)
updateAccount(a2);
new
new
loadAccount(“1”);
a1
loadAccount(“2”);
a2
debit(“300.00”)
credit(“300.00”)
updateAccount(a1);
Use Case : Bank Money Transfer
14
Ramkrishna IT Systems
Spring’s Configuration
Support
• Spring provides support for assembling such an
application system from its parts
– Parts do not worry about finding each other
– Any part can easily be swapped out
15
Ramkrishna IT Systems
TransferServiceImpl
Money Transfer System
Assembly
Spring
Part 2
Assembly
JdbcAccountRepository
Part 1
(1) new JdbcAccountRepository(…);
(2) new TransferServiceImpl();
(3) service.setAccountRepository(repository);
8
16
Ramkrishna IT Systems
}
Parts are Just Plain Java Objects
public void setAccountRepository(AccountRepository ar) {
accountRepository = ar;
}
…
}
Part 1
Depends on service interface; conceals complexity of
implementation; allows for swapping out implementation
Part 2
public class JdbcAccountRepository implements
AccountRepository {
…
Implements a service interface
public class TransferServiceImpl implements TransferService {
private AccountRepository accountRepository;
17
Ramkrishna IT Systems
Enterprise Integration
• Enterprise applications do not work in isolation
• They require enterprise services and resources
Database Connection Pool
Database Transactions
Security
Messaging
Remote Access
Caching
18
Ramkrishna IT Systems
Spring Enterprise Integration
• Spring helps you integrate powerful enterprise
services into your application
– While keeping your application code simple and
testable
• Plugs into all Java EE™ application servers
– While capable of standalone usage
19
Ramkrishna IT Systems
TransferServiceImpl
Enterprise Money Transfer
with Spring
Spring
JdbcAccountRepository
DataSource
For DB Connection Pooling
13
TransactionManager
For DB Transactions
MBean
Exporter
For JMX Management
Ramkrishna IT Systems
20
Ramkrishna IT Systems
Simple Application Code
public class TransferServiceImpl implements TransferService {
@Transactional
public TransferConfirmation transfer(MonetaryAmount amount, in srcAccountId, int
targetAccountId ){
Account src = accountRepository.loadAccount(srcAccountId);
Account target = accountRepository.loadAccount(targetAccountId);
src.debit(amount);
target.credit(amount);
accountRepository.updateAccount(src);
accountRepository.updateAccount(target);
return new TransferConfirmation(...);
}
}
Tells Spring to run this method
in a database transaction
Ramkrishna IT Systems
21
Ramkrishna IT Systems
Spring makes data access easier to
– Manage resources for you
– Provide API helpers
– Support all major data access technologies
It also Supports Integration of
Hibernate
iBatis
JPA
Data Access
22
Ramkrishna IT Systems
•
•
Acquisition of the connection
Participation in the transaction
•
•
•
•
Execution of the statement
Processing of the result set
Handling of any exception
Release of the connection
All handled
by Spring
Spring JDBC in a Nutshell
Spring's JDBC helper class
int count = jdbcTemplate.queryForInt(
"SELECT COUNT(*) FROM CUSTOMER");
23
Ramkrishna IT Systems
Spring Framework History
• http://www.springsource.org/download
• Spring 3.0 (released 12/09)
– Requires Java 1.5+ and JUnit 4.7+
– REST support, JavaConfig, SpEL, more annotations
• Spring 2.5 (released 11/07)
– Requires Java 1.4+ and supports JUnit 4
– Annotation DI, @MVC controllers, XML namespaces
• Spring 2.0 (released 10/06)
– Compatible with Java 1.3+
– XML simplification, async JMS, JPA, AspectJ support
24
Ramkrishna IT Systems
Download and install STS 2.3.3.M2 from SpringSource.com:
• Eclipse Based
• Has Spring Plug-ins
• Auto-Completion for Spring Config files
• Comes with Tomcat plugged-in
•Comes with Junit-plugged-in
25
Ramkrishna IT Systems
Lab -1 : 30 minutes
Use STS for creating non-Spring App
26
Ramkrishna IT Systems
Dependency Injection : Alternatives
• Creation using singletons
• Factory Pattern
• Reflection with Strategy Pattern
• Decorator
• Service Locator
27
Ramkrishna IT Systems
Dependency Injection : Responsibility of co-ordination and
collaboration is taken away from objects
• Decoupling : Program-to-Interface principle
• Dependency graph
• Clean code
• Enforcing immutability if required
• Enforcing initialization
• Runtime changes in dependency rules
• Objects focus on their task and not worried about availability
of their dependent objects
28
Ramkrishna IT Systems
Steps :
1.Identify the dependencies
2.Decide optional dependancies
3.Wire them together in XML file
4.Instantiate ApplicationContext(container)
5.Get Instance by calling getBean() method
Dependency Injection : Using Spring
29
Ramkrishna IT Systems
With Spring
ApplicationContext ctx = …
Bank bank = ctx.getBean(“bankService”);
bank.withdraw(1234, 500);
Bank Service Example
Without Spring :
AccountRepository repos = new AccountRepositoryImpl();
Bank bank = new BankImpl(repos);
bank.withdraw(1234, 500);
No need to instantiate AccountRepository, No
knowledge of Bank Implementation class
30
Ramkrishna IT Systems
With Spring
ApplicationContext ctx = …
Bank bank = ctx.getBean(“bankService”);
bank.withdraw(1234, 500);
Bank Service Example
Spring Bean Configuration File :
<bean id="bankService" class="bank.server.internal.BankImpl">
<constructor-arg ref="accountRepo"/>
</bean>
<bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl">
</bean>
“bankService” must match with bean id
31
Ramkrishna IT Systems
Equivalent to
AccountRepository accountRepo = new bank.server.internal.AccountRepositoryImpl();
Bank Bank = new BankImpl(accountRepo);
Bank Service Example
Spring Bean Configuration File :
<bean id="bankService" class="bank.server.internal.BankImpl">
<constructor-arg ref="accountRepo"/>
</bean>
<bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl">
</bean>
Application Context
bankService Instance of BankImpl
accountRepo Instance of
AccountRepositoryImpl
32
Ramkrishna IT Systems
Lab -2 : 40 minutes
Use STS for creating Spring App
33
Ramkrishna IT Systems
Equivalent to
AccountRepository accountRepo = new
bank.server.internal.AccountRepositoryImpl();
DBAccessRService dbAccessService = new bank.server.internal.DBAccessServiceImpl();
Bank Bank = new BankImpl(accountRepo, dbAccessService);
Constructor Dependency Injection
Spring Bean Configuration File :
<bean id="bankService" class="bank.server.internal.BankImpl">
<constructor-arg ref="accountRepo"/>
<constructor-arg ref=“dbAccessService"/>
</bean>
<bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl">
</bean>
</bean>
<bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl">
</bean>
2 class instances are expected to
be passed to constructor
34
Ramkrishna IT Systems
Equivalent to
AccountRepository accountRepo = new bank.server.internal.AccountRepositoryImpl();
DBAccessRService dbAccessService = new bank.server.internal.DBAccessServiceImpl();
Bank Bank = new BankImpl();
bank.setAccountRepository(accountRepo );
bank. setDBAccess(dbAccessService);
Setter Dependency Injection
Spring Bean Configuration File :
<bean id="banService" class="bank.server.internal.BankImpl">
<property name=“accountRepository” ref="accountRepo"/>
<property name=“dBAccess” ref=“dbAccessService"/>
</bean>
<bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl">
</bean>
</bean>
<bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl">
</bean>
2 class instances are expected to
be passed to Setters
35
Ramkrishna IT Systems
Setter vis-à-vis constructor Dependency Injection
Constructor Dependency : When Do I Use
Enforce mandatory dependancy
Promote Immutability(by assigning dependencies to final vars)
Setter Dependency : When do I Use
Allow optional dependencies
Allow defaults
Config file is more readable(property names are generally
meaningful)
Inherited automatically(Constructors are required to be written in
sub-classes)
36
Ramkrishna IT Systems
Mix-and –Match
<bean id="banService" class="bank.server.internal.BankImpl">
<constructor-arg ref="accountRepo"/>
<property name=“dbAccess”ref=“dbAccessService"/>
</bean>
<bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl">
</bean>
</bean>
<bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl">
</bean>
Setter vis-à-vis constructor Dependency Injection
37
Ramkrishna IT Systems
Mix-and –Match
<bean id="banService" class="bank.server.internal.BankImpl">
<constructor-arg ref="accountRepo"/>
<property name=“dbAccess”ref=“dbAccessService"/>
</bean>
<bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl">
</bean>
</bean>
<bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl">
</bean>
Reccomendations
Use Constructor DI for required properties
Use Setter Injection for optional properties and defaults.
Be consistent in the approach.
38
Ramkrishna IT Systems
<bean id=“someService" class=“example.SomeServiceImpl">
<property name=“balance” value=“10000"/>
</bean>
Container takes care of auto conversion of scalar values .
Throws Exception if type mis-match(non-convertible types)
Injection for scalars
Injecting Collections
class BankImpl implements Bank{
Collection<Account> accounts;
public void showAccount(){
for(Account acct : accounts){
System.out.println(acct.toString());
}
}
39
Ramkrishna IT Systems
<bean id=“bankService" class=“bank.server.BankImpl">
<property name=“accounts”>
<list>
<ref bean =“current” >
<ref bean =“savings” />
<ref bean = “FD” />
<ref bean =“housingLoan />
</list>
</bean>
Injecting Collections
class BankImpl implements Bank{
Collection<AccountService> accountServices;
BankImpl(Collection<AccountService> accounts){
this. accountServices = accounts;
}
public void showAccountServices(){
for(AccountService acct : accountServices){
System.out.println(acct.toString());
}
}
<set>
<ref bean =“current” >
<ref bean =“savings” />
<ref bean = “FD /
<ref bean =“housingLoan”/>
<ref bean =“housingLoan”/> //duplicate entry
</set>
40
Ramkrishna IT Systems
<bean id=“bankService" class=“bank.server.BankImpl">
<property name=“accounts”>
<map>
<entry key=“CurrentAccount” value-ref=“current” >
<entry key=“SaningsAccount” value-ref =“savings” />
<entry key=“FixedDeposit” value-ref = “FD” />
</map>
</bean>
Injecting Collections
class BankImpl implements Bank{
Map<AccountService> accountServices;
BankImpl(Collection<AccountService> accounts){
this. accountServices = accounts;
}
public void showAccountServices(){
for(String accountType : accountServices.keySet()){
System.out.println(accountServices.get(acctType).toString());
}
}
<map>
<entry key-ref=“someBean”
value-ref “otherbean” />
</map >
OR
<map>
<entry key=“someScalarType”
value=“someScalarType” />
</map>
41
Ramkrishna IT Systems
<bean id=“bankService" class=“bank.server.BankImpl">
<constructor-arg name=“accounts”>
<props>
<prop key=“CurrentAccount”>current </prop>
<prop key=“SaningsAccount” >savings</prop>
<prop key=“FixedDeposit” >FD</prop>
</props>
</bean>
Injecting Collections : Properties
class BankImpl implements Bank{
Map<AccountService> accountServices;
BankImpl(Properties accounts){
this. accountServices = accounts;
}
public void showAccountServices(){
for(String accountType : accountServices.keySet()){
System.out.println(accountServices.get(acctType).toString());
}
}
<props>
<prop key=“keyString”
>value</prop>
</props>
42
Ramkrishna IT Systems
DI Advance Options:Inner-beans
<bean id="bankService" class="bank.server.internal.BankImpl" abstract="true" >
<constructor-arg >
<bean class="bank.server.internal.AccountRepositoryImpl" />
</constructor-arg>
</bean>
Implications :
1. Inner beans are always lazy initialized as opposed to early-init of outer beans
2. Inner beans are always scoped to scope of the outer bean
43
Ramkrishna IT Systems
Options To do following
1. Control number of instances of a specific bean :
1 Per application (scope=“singleton” this is default)
1 Per usage (scope”prototype”)(This is useful if domain classes are used as
beans)
1 Per user-request (If HTTP capable Spring context is used using SpringMVC then
scope=“request”)
1 per session (If HTTP capable Spring context is used using SpringMVC then
scope=“session”)
Singleton here is different from singleton pattern. Here singleton does not mean
multiple instances cannot be created, all it means is application context keeps
only one copy.
c tx.getBean(“beanName”) method uses the scope attribute to decide the
creation
<bean id=“someId” class=“someClass” scope=“prototype” />
Controlling Bean Creation
44
Ramkrishna IT Systems
Bean Scopes : singleton(default)
45
Ramkrishna IT Systems
Bean Scopes : prototype
Destruction of prototypes is NOT managed by container .
You have to do the clean-up(call destroy method etc) explicitly in your
client code
OR create custom-BeanPostProcessor to do it for you.
46
Ramkrishna IT Systems
Bean Scopes : prototype
Destruction of prototypes is NOT managed by container .
You have to do the clean-up(call destroy method etc) explicitly in your
client code(You need to type-cast ctx to
ConfigurableApplicationContext and call close()
OR create custom-BeanPostProcessor to do it for you.
Prototypes are not eager-initialized unlike singletons
Prototypes are injected once per singleton dependants.
Mutliple calls to getBean(“bankService”) will not refresh(re-instantiate)
the prototype.
47
Ramkrishna IT Systems
Get same bean class with different id’s and with some common DI.
Over ride few property values.
Minimize repetitive declarations in xml
parent attribute for sub-beans
No class attribute
abstract=“true” for parent bean
DI Advance Options:sub-beans
<bean id="bankService" class="bank.server.internal.BankImpl" abstract="true" scope="singleton" >
<constructor-arg >
<bean class="bank.server.internal.AccountRepositoryImpl" scope="singleton"/>
</constructor-arg>
<constructor-arg>
<set>
<ref bean="current" />
<ref bean="saving" />
<ref bean="loan"/>
</set>
</constructor-arg>
<property name="bankName" value="RBI" />
<property name="branchCode" value="1234" />
</bean>
<bean id="sbi" parent="bankService" >
<property name="bankName" value="StateBank" />
</bean>
<bean id="axis" parent="bankService" >
<property name="branchCode" value="345" />
</bean>
48
Ramkrishna IT Systems
Parent bean could be an abstract class an interface, a concrete class or may
not be a class at all( it is just a set of properties that child beans share).
abstract=“true” for parent bean
Child beans are actually classes which are un-related classes sharing
common properties.
Child beans can overwrite the property values.
DI Advance Options:sub-beans with only property
inheritance
<bean id="bankService" abstract="true" >
<constructor-arg >
<bean class="bank.server.internal.AccountRepositoryImpl" />
</constructor-arg>
<constructor-arg>
<props>
<prop key="CURRENT ACCOUNT" >hello </prop>
<prop key="SAVING ACCOUNT">saving</prop>
<prop key="LOAN ACCOUNT" >loan </prop>
</props>
</constructor-arg>
<property name="branchCode" value="1234" />
<property name="bankName" value="SBI"></property>
</bean>
<bean id="sbi" class="bank.server.internal.SBI" parent="bankService" >
</bean>
<bean id="axis" class="bank.server.internal.AXIS" parent="bankService" >
<property name="branchCode" value="345" />
<property name="bankName" value="AXIS"></property>
</bean>
</bean>
49
Ramkrishna IT Systems
Allows runtime injection of methods into java classes(like
template method pattern)
2 Forms
Getter Injection : Returns a different spring bean at runtime
Method replacements : Runtime injection of different
implementation
Injecting Methods
1.Getter Injection :
•Bean class could be abstract(or concrete)
•abstract class Magician {
• abstract MagicBox getBox();
•}
•The method which needs to be replaced(injected) at runtime comes from some
other concrete class.
•To replace method, bytecode is instrumented by CGLIB at runtime and a
subclass of the current class is created and the method is injected into it
•So class who’s method is to be replaced can not be final, method cannot be
final either.
50
Ramkrishna IT Systems
Allows runtime injection of methods into java classes(like template method
pattern)
2 Forms
Method injection using lookup-method: This is a getter Injection which
returns a different bean at runtime.
Method Injection using Method Replacer:
Injecting Methods
Choo Mantar !!
51
Ramkrishna IT Systems
Allows runtime injection of methods into java classes(like
template method pattern)
2 Forms
Method replacements :
Injection Using Method-replacer:
Injecting Methods
2. Method Injection using Method-Replacer :
public class ElephantReplacer implements MethodReplacer {
public Object reimplement(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
//System.out.println("Object whos method is to be
replaced"+arg0.toString()+" Name of Method "+arg1.getName()+" MYSORE ELEPHANT "+arg2[0]);
return "MYSORE ELEPHANT ";
}
}
52
Ramkrishna IT Systems
Using non-managed beans (User instantiated beans) with Spring DI
These are normally Domain Beans(Pojos) created by say hibernate
session.load(). You want these objects to be monitored for dependency etc.
by Spring.
Use VM args to enable Load Time Weaving of AspectJ’s Aspect
-javaagent:C:core-spring-3.1.0.RELEASErepositoryorgaspectjaspectjweaver1.6.8aspectjweaver-1.6.8.jar
Injecting Non-spring beans
import org.springframework.beans.factory.annotation.Configurable;
@Configurable("magician")
public class Magician {
String magicwords;
MagicBox box;
…..}
<context:spring-configured />
<bean id="magician" class="com.rits.Magician" >
<property name="box" ref="magicbox"></property>
<property name="magicwords" value="Choo Mantar !!" />
</bean>
<bean id="magicbox" class="com.rits.MagicBoxImpl" />
53
Ramkrishna IT Systems
Lab -3 : 45 minutes
Using Setter Injection, Collection Injections
54
Ramkrishna IT Systems
<bean id=“bankService" class=“bank.server.BankImpl">
<property name=“accountService” ref=“acctRepo” />
</bean>
<bean id=“acctRepo” class=“bank.server.internal.AccountRepositoryImpl” />
OR
<bean id=“bankService" class=“bank.server.BankImpl“ autowire=“byName” />
<bean id=“acctRepo” class=“bank.server. internal.AccountRepositoryImpl” />
AutoWiring
Autowiring of 4 types
1. byName : Attempts to find a bean in the container whose name(or ID) is the same as the
name of the property being wired(injected)
2. byType : Attempts to find a single bean in the container whose type matches the type of
the property being wired. If not found it ignores, if multiple macthes found then throws
org.springframework.beans.factory.UnsatisfiedDependencyException
3.constructor : Tries to match up one or more beans in the container with the parameters of
one of the constructors of the bean being wired. In case of ambiguity it throws
org.springframework.beans.factory.UnsatisfiedDependencyException
4. autodetect : Tries to apply constructor stretagy first if matching constructor found then it
will use contructor injection if not then will apply byType strategy and is matching type found
then applies setterInjection if neither is found then leaves property un-initialized.
55
Ramkrishna IT Systems
Special attributes : factory-method/init-
method/destroy-method
1
<bean id=“someId” class=“someClass” factory-method=“getInstance() />
A static object creation method can be invoked instead of calling
constructor. Works for objects with private constructors and true
singletons.
<bean id=“someBean” class=“someClass” init-method=“doInit” />
<bean id=“someBean” class=“someClass” destroy-method=“doDestroy” />
Controlling Bean Creation
56
Ramkrishna IT Systems
Special attributes : factory-bean Option-1 : POJO
factory
Useful for existing factory classes
<bean id=“someId” class=“someClass” factory-bean=“someFactory” factory-
method=“getInstance” />
<bean id=“someFactory” class=“someFactoryClass” />
An instance object creation method can be invoked instead of calling
constructor. Works for objects with private constructors and true
singletons
Bean Creation Using factory-bean
57
Ramkrishna IT Systems
Option-II Use FactoryBean implementation
<bean id=“someFactoryId” class=“someFactoryClass” />
<bean id=“bankService” class=“BankImpl” >
<property name=“service” ref=“someFactoryId” />
</bean>
A Dependency Injection of the Object returned by the Template
Factory is done transparently (calling getObject Method)
e.g.
Class SomeFactoryClass implements FactoryBean<SomeService>{
public SomeService getObject() throws Exception { return new
SomeSevice() ;}
Bean Creation : Using FactoryBean interface
58
Ramkrishna IT Systems
FactoryBean
• Spring uses FactoryBean Template
interface
RemoteProxies are created using FactoryBean
– DataSources are created using FactoryBean
for accessing Hibernate, iBatis etc.
59
Ramkrishna IT Systems
ApplicationContext
• Spring provides a lightweight container
called “ApplicationContext”
– 3 flavours for resource(config file) loading
– 1. new ClassPathXmlApplicationContext(“com/sungard/application-config.xml”);
– $CLASSPATH/com/sungard/application-config.xml”
– 2. new FileSystemXmlApplicationContext(c:somedirapplication-config.xml”);
– OR
– new FileSystemXmlApplicationContext(../application-config.xml”);
– 3. XmlWebApplicationContext : Created by WebCOntainers resource loading happens
relative to WEB-INF/
60
Ramkrishna IT Systems
ApplicationContext
• Loading multiple config files
• ApplicationContext ctx =
• new ClassPathXmlApplicationConext(new String[]{“application-config.xml”,
“oracle-infra-config.xml” , file:../someOther-config.xml”});
• Separate files for Infrastructure config than
actual application beans.
61
Ramkrishna IT Systems
Phases of the Application
Lifecycle
Initialization
• Prepares for use
• Application
services
– Are created
– Configured
– May allocate
system resources
• Application is not
usable until this
phase is complete
Use
• Used by clients
• Application
services
– Process client
requests
– Carry out
application
behaviors
• 99.99% of the
time is spent in
this phase
Destruction
• Shuts down
• Application
services
– Release any
system resources
– Are eligible for
garbage
collection
11
62
Ramkrishna IT Systems
Application Initialization
When We create an instance of the ApplicationContext :
Initialization is Complete
During applicationContext Creation, What Happens?
(when we call new CLassPathXMLApplicationContext(…)
1. Loading of Bean Definitions from config files
2. Creates dependancy graph
3. All singleton beans and pre-instantiated (unless lazy-init=“true” )
4. Initialization of bean Instances
63
Ramkrishna IT Systems
Application Initialization :
Loading Bean Definitions
•The XML files are parsed.
Bean Definitions are loaded into the context’s
BeanFactory
Special Beans “BeanFactoryPostProcessor” are
invoked
These special beans can modify the bean
definitions before creating the objects.
64
Ramkrishna IT Systems
Load Bean Definitions
application-config.xml
<beans>
Application Context
BeanFactory
transferService
accountRepository
dataSource
postProcess(BeanFactory)
BeanFactoryPostProcessors
<bean id=“transferService” …
<bean id=“accountRepository”…
</beans>
test-infrastructure-config.xml
<beans>
<bean id=“dataSource” …
</beans>
Can modify the definition of
any bean in the factory
before any objects are created
17
65
Ramkrishna IT Systems
BeanFactoryPostProcessor
•An Extension Point to modify bean definitions programatically before
loading bean definitions
•Several useful special BeanFactoryPostProcessor beans are provided
by Spring
• e.g. PropertyPlaceholderConfigurer
It substitutes ${variables} in bean definitions with values
from .properties files
CustomEditorConfigurer
It loads custom editors into beanfactory.
You can write your own by implementing BeanFactoryPostProcessor interface
66
Ramkrishna IT Systems
Custom Property Editors
class Contact{
public PhoneNumber getPhone() {
return phone;
}
public void setPhone(PhoneNumber phone) {
this.phone = phone;
}
public class PhoneNumber {
String areaCode;
String stdCode;
String number;
public PhoneNumber(String areaCode, String stdCode, String number) {
super();
this.areaCode = areaCode;
this.stdCode = stdCode;
this.number = number;
}
<bean id="contact" class="com.rits.training.Contact" >
<property name="phone" value="512-230-9630" />
</bean>
Need to convert
String into
PhoneNumber
67
Ramkrishna IT Systems
mport java.beans.PropertyEditorSupport;
public class PhoneEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
String stripped = stripOutNonNumerics(text);
String areaCode = stripped.substring(0,3);
String prefix = stripped.substring(3,6);
String number = stripped.substring(6);
PhoneNumber phone = new PhoneNumber(areaCode,prefix, number);
this.setValue(phone);
}
private String stripOutNonNumerics(String original){
StringBuffer allNumeric = new StringBuffer();
for(int i=0; i < original.length(); i++){
char c = original.charAt(i);
if(Character.isDigit(c)){
allNumeric.append(c);
}
68
Ramkrishna IT Systems
We should tell Spring about our custom PhoneEditor
<bean id="contact" class="com.rits.training.Contact" >
<property name="phone" value="512-230-9630" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.rits.training.PhoneNumber">
<bean id="phoneEditor" class="com.rits.training.PhoneEditor" />
</entry>
</map>
</property>
</bean>
CustomEditorConfigurer is a BeanFactoryPostProcessor. It registers PhoneEditor with
BeanFactory, so BeanFactory would invoke this before creating Contact bean.
69
Ramkrishna IT Systems
BeanFactoryPostProcessor : PropertyPlaceholderConfigurer
<property name=“URL” value=“${datasource.url}” />
<property name=“user” value=“${datasource.user}” />
<bean class=“org.springframework.beans.factory.config.
PropertyPlaceholderConfigurer”>
<property name=“location” value=“/WEB-INF/datasource.properties” />
File where the variable values reside
datasource.url=jdbc:oracle:thin:@localhost:1521:BANK
datasource.user=moneytransfer-app
</bean>
</beans>
datasource.properties
Variables to replace
Easily editable
21
<beans>
<bean id=“dataSource” class=“com.oracle.Jdbc.pool.OracleDataSource”>
70
Ramkrishna IT Systems
Simplifying configuration with
<context:property-placeholder>
<beans ... >
<bean id=“dataSource” class=“com.oracle.Jdbc.pool.OracleDataSource”>
<property name=“URL” value=“${datasource.url}” />
<property name=“user” value=“${datasource.user}” />
</bean>
<context:property-placeholder location=“datasource.properties” />
</beans>
Creates the same PropertyPlaceholderConfigurer
bean definition in a more concise fashion
71
Ramkrishna IT Systems
Registering for an Initialization
Callback with InitializingBean
• Initialization technique used prior to Spring 2.5
– Disadvantage: Ties your code to the framework
– Advantage: The only way to enforce initialization
code should run (not affected by configuration changes)
package org.springframework.beans.factory;
public interface InitializingBean {
public void afterPropertiesSet();
}
PropertyPlaceholderConfigurer
20
How PropertyPlaceholderConfigurer
Works
Spring Application Context
(after bean definitions are loaded)
postProcess(BeanFactory)
Bean definition
“dataSource”
URL=${datasource.url}
user=${datasource.user}
Bean definition
“dataSource”
URL=Jdbc:oracle:…
user=moneytransfer-app
72
Ramkrishna IT Systems
Steps involved in Initializing Bean Instances
• Each bean is eagerly instantiated by default
– Created in the right order with its dependencies
injected
• After dependency injection each bean goes
through a post-processing phase
– Where further configuration and initialization can
occur
• After post processing the bean is fully initialized
and ready for use
– Tracked by its id until the context is destroyed
73
Ramkrishna IT Systems
Bean Initialization Steps
Bean
Instantiated
Dependencies
InJected
Bean Post
Processed
Bean
Ready
For Use
74
Ramkrishna IT Systems
Bean Post Processing
• Bean post processing can be broken down into
two steps
– Initialize the bean if instructed
– Call special BeanPostProcessors to perform additional
configuration
75
Ramkrishna IT Systems
Initialize the Bean if
Instructed
• A bean can optionally register for one or more
initialization callbacks
– Useful for executing custom initialization behaviors
• There's more than one way to do it
– JSR-250 @PostConstruct
– <bean/> init-method attribute
– Implement Spring's InitializingBean interface
76
Ramkrishna IT Systems
Registering for Initialization with @PostConstruct
public class TransferServiceImpl {
@PostConstruct
void init() {
// your custom initialization code
Tells Spring to call init
after DI
No restrictions on
method name or visibility
}
}
• This is the preferred initialization technique
– Flexible, avoids depending on Spring APIs
– Requires Spring 2.5 or better
30
77
Ramkrishna IT Systems
Enabling Common Annotation- Based Initialization
• @PostConstruct will be ignored unless Spring is
instructed to detect and process it
<beans>
<bean id=“transferService” class=“example.TransferServiceImpl” />
<bean class=“org.springframework.context.annotation.
CommonAnnotationBeanPostProcessor” />
</beans>
Detects and invokes any
methods annotated with
@PostConstruct
78
Ramkrishna IT Systems
Registering for an Initialization
Callback with InitializingBean
• Initialization technique used prior to Spring 2.5
– Disadvantage: Ties your code to the framework
– Advantage: The only way to enforce initialization
code should run (not affected by configuration changes)
package org.springframework.beans.factory;
public interface InitializingBean {
public void afterPropertiesSet();
}
79
Ramkrishna IT Systems
Simplifying Configuration with
<context:annotation-config>
<beans>
<bean id=“transferService” class=“example.TransferServiceImpl” />
<context:annotation-config/>
</beans> Enables multiple BeanPostProcessors, including:
• RequiredAnnotationBeanPostProcessor
• CommonAnnotationBeanPostProcessor
80
Ramkrishna IT Systems
Initializing a Bean You Do Not Control
•
Use init-method to initialize a bean you do not
control the implementation of
<bean id=“current”
class="bank.server.internal.CurentAccount"
init-method=“initialize”>
…
</bean>
Method can be any visibility, but must have no arguments
34
Class with no Spring dependency
81
Ramkrishna IT Systems
Initialization : @Required
•RequiredAnnotationBeanPostProcessor
e.g.
@Required
public void setInterestRate(float interestRate) {
this.interestRate = interestRate;
System.out.println("Saving Account : interest ");
}rate property set”);
If interestRate property of this class is not configured in config file for DI,
container would throw
org.springframework.beans.factory.BeanCreationException
This is a useful technique for enforcing the initialization
82
Ramkrishna IT Systems
Destroying : @PreDestroy
•BeanPostProcessor
Called when ctx.close() is invoked.
@PreDestroy
public void releaseResources() {
System.out.println(“Resources released”);
}
This is a useful technique for enforcing the release of some resources like DB
connections etc.
83
Ramkrishna IT Systems
Destroying : destroy-method
•BeanPostProcessor
Called when ctx.close() is invoked.
<bean id=“somBean” class=“SomeClass” destroy-method=“someMethod” />
This is a useful technique for enforcing the release of some resources like DB
connections etc.
43
Topics in this session
• Introduction to Spring's XML namespaces
• The lifecycle of a Spring application context
– The initialization phase
– The use phase
– The destruction phase
• Bean scoping
Use DestructionInitialization
84
Ramkrishna IT Systems
Destroying : destroy-method
•BeanPostProcessor
Called when ctx.close() is invoked.
<bean id=“somBean” class=“SomeClass” destroy-method=“someMethod” />
This is a useful technique for enforcing the release of some resources like DB
connections etc.
43
Topics in this session
• Introduction to Spring's XML namespaces
• The lifecycle of a Spring application context
– The initialization phase
– The use phase
– The destruction phase
• Bean scoping
Use DestructionInitialization
44
The Lifecycle of a Spring Application
Context (2) - The Use Phase
• When you invoke a bean obtained from the
context the application is used
• But exactly what happens in this phase?
ApplicationContext context = // get it from somewhere
// Lookup the entry point into the application
TransferService service =
(TransferService) context.getBean(“transferService”);
// Use it!
service.transfer(new MonetaryAmount(“50.00”), “1”, “2”);
85
Ramkrishna IT Systems 45
Inside The Bean Request
(Use) Lifecycle
• If the bean is just your raw object it is simply
invoked directly (nothing special)
TransferServiceImpl
transfer(“$50”, “1”, 2”)
transfer(“$50”, “1”, 2”)
TransferServiceImpl
• If your bean has been wrapped in a proxy
things get more interesting
Spring Proxy
86
Ramkrishna IT Systems 45
Inside The Bean Request
(Use) Lifecycle
• If the bean is just your raw object it is simply
invoked directly (nothing special)
TransferServiceImpl
transfer(“$50”, “1”, 2”)
transfer(“$50”, “1”, 2”)
TransferServiceImpl
• If your bean has been wrapped in a proxy
things get more interesting
Spring Proxy
87
Ramkrishna IT Systems 45
TransferServiceImpl
transfer(“$50”, “1”, 2”)
transfer(“$50”, “1”, 2”)
TransferServiceImpl
• If your bean has been wrapped in a proxy
things get more interesting
Spring Proxy
88
Ramkrishna IT Systems
Annotation-Based
Dependency Injection
Introducing Spring’s Annotations for
Dependency Injection
89
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
90
Ramkrishna IT Systems
Configuration
Instructions
How Spring Works
Your Application Classes (POJOs)
Spring
Application Context
Creates
Fully configured
application system
Ready for use
91
Ramkrishna IT Systems
The Approach You’re Used to
public class TransferServiceImpl implements TransferService {
public TransferServiceImpl(AccountRepository ar) {
this.accountRepository = ar;
}
…
}
public class JdbcAccountRepository implements AccountRepository {
public void setDataSource(DataSource ds) {
this.dataSource = ds;
}
…
}
4
Use POJOs with constructor arguments
and/or property setters for configuration
92
Ramkrishna IT Systems
The Approach You’re Used to
<beans>
<bean id=“transferService” class=“app.impl.TransferServiceImpl””>
<constructor-arg ref=“accountRepository” />
</bean>
<bean id=“accountRepository” class=“app.impl.JdbcAccountRepository””>
<property name=“dataSource” ref=“dataSource” />
</bean>
<bean id=“dataSource” class=“com.oracle.jdbc.pool.OracleDataSource””>
<property name=“URL” value=“jdbc:oracle:thin:@localhost:1521:BANK” />
<property name=“user” value=“moneytransfer-app” />
</bean>
</beans>
5
<bean> defines a bean
Dependency Injection
93
Ramkrishna IT Systems
Alternative Approaches
• Bean definitions can also be defined and
configured in Java
• Or by using annotations in Spring-managed classes
• Both are alternatives to XML approach
– Not intended as complete replacements
– Can be used together
94
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
95
Ramkrishna IT Systems
Java-based Approach
• Spring 3.0 introduces Java-based configuration
– Based on the old JavaConfig project
• Use Java code to define and configure beans
– Configuration still external to POJO classes to be
configured
– More control over bean instantiation and configuration
– More type-safety
• Still produces bean definitions
– Spring remains in charge applying post-processors etc.
96
Ramkrishna IT Systems
•The central artifact in Spring's new Java-configuration support is
the @Configuration-annotated class.
•These classes consist principally of @Bean-annotated methods
•These Methods define instantiation, configuration, and initialization logic for objects to
be managed by the Spring IoC container.
•Annotating a class with the @Configuration indicates that the class can be used by the
Spring IoC container as a source of bean definitions.
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
<beans>
<bean id="myService" class=“com.rits.training.MyServiceImpl"/>
</beans>
XML Way
Spring3.0 Java Configuration Class
97
Ramkrishna IT Systems
@Configuration-annotated classes are sub-classed at load time by CGLIB so
They should not be final
They should have no-arg non-private constructor
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
Getting bean instances using AnnotationConfigApplicationContext.
Class client{
public static void main(String[] args){
AnnotationConfigApplicationContext ctx =
new AnnotaionConfigApplicationContext(AppConfig.class)
}
Spring3.0 Java Configuration Class
No XML
Just Use
@Configuration
class Name
98
Ramkrishna IT Systems
@Mix-Match of Java-Based and XML based configuration
(@Configuration –centric)
@ImportResource("test-infrastructure-Java_Based_config.xml")
public class BankConfig {
private @Value(“#{jdbcProperties.oracleURL}") String url;
private @Value(“#{jdbcProperties.oracleUser}") String username;
private @Value(“#{jdbcProperties.oraclePassword}") String password;
private @Value(“#{jdbcProperties.oracleDriver}") String driver;
…..
public @Bean(scope=“singleton”) DriverManagerDataSource dataSource() {
return new DriverManagerDataSource(url, username, password);
}
testdb.properties
oracleDriver=oracle.jdbc.driver.OracleDriver
oracleURL=jdbc:oracle:thin:@localhost:1521:XE
oracleUser=system
oraclePassword=system
Spring3.0 Java Configuration Class
<util:properties id="jdbcProperties"
location="testdb.properties"/>
test-infrastructure-…xml
99
Ramkrishna IT Systems
@Configuration("configBank")
@ImportResource("test-infrastructure-Java_Based_config.xml")
public class BankConfig {
private @Value("#{jdbcProperties.oracleURL}") String url;
private @Value("#{jdbcProperties.oracleUser}") String username;
…..
@Bean(name="bankService")
@Scope("prototype")
Bank bankService(){
Collection<AccountService> accts = new ArrayList<AccountService>();
accts.add(currentAccount());
accts.add(loan());
accts.add(saving());
return new BankImpl(accountRepository(),accts);
}
@Bean(name="acctRepo")
AccountRepository accountRepository(){
return new AccountRepositoryImpl(dataSource());
}
@Bean(name="current")
AccountService currentAccount(){
CurentAccount acct= new CurentAccount("Ramkrishna IT",1000000);
acct.setAcctNo(123456789);
return acct;
} public @Bean DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(url, username,
password);
dataSource.setDriverClassName(driverClassName);
return dataSource;
}
}
100
Ramkrishna IT Systems
Enabling Java-based Approach
• Making this work requires two steps:
– Define config class as Spring Bean
– Add <context:annotation-config/>
<beans xmlns="http://www.springframework.org/schema/beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="...">
<context:annotation-config/>
Turns on checking of configuration
annotations for beans declared
in this context
101
Ramkrishna IT Systems
Usage - Nothing Changes!
// Create the application from the configuration
ApplicationContext context =
new ClassPathXmlApplicationContext(“application-config.xml””);
// Look up the application service interface
Bank service = (Bank) context.getBean(“bankService””);
// Use the application
102
Ramkrishna IT Systems
Implementing @Bean Methods
• Configuration in Java: call any code you want
– Not just constructors and property setters
• May not be private
• Method name becomes bean name
• Call @Bean method to refer to bean in same class
– We'll show how to refer to external beans later
• Same defaults as XML: beans are singletons
– Use @Scope annotation to change scope
@Bean @Scope("prototype")
public StatefulService service() {
…
103
Ramkrishna IT Systems
@Bean Lifecycle
• Init- and destroy methods can be specified
– Using attributes of the annotation
– init really isn't required, can just call method yourself
@Bean(destroyMethod="close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:derby:rewardsdb");
// can call init method here if you need to
return dataSource;
}
104
Ramkrishna IT Systems
Implementing @Configuration
Classes
• Must have default constructor
• Multiple @Configuration classes may exist
• Can import each other using @Import
– Equivalent to <import/> in XML
– Means included classes don't have to be defined as
Spring beans anymore
@Import({SecurityConfig.class, JmxConfig.class})
@Configuration
public class RewardsConfig {
…
}
105
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
106
Ramkrishna IT Systems
Annotation-based
Configuration
• Spring 2.5 introduced annotation-based
configuration as another alternative to XML
• Moves configuration instructions into your code
– Unlike XML or Java-based approaches
• Can be used in combination with the other
approaches
Annotation injection is performed before XML injection, thus the latter
configuration will override the former for properties wired through both
approaches.
107
Ramkrishna IT Systems
The Annotation-Based Approach
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(AccountRepository ar) {
this.accountRepository = ar;
}
…
public class JdbcAccountRepository implements AccountRepository {
@Autowired
public void setDataSource(DataSource ds) {
this.dataSource = ds;}
…
}
17
Spring automatically tries to wire this
}
108
Ramkrishna IT Systems
The Annotation-Based Approach
<beans>
<context:annotation-config/>
<bean id=“transferService”
class=“app.impl.TransferServiceImpl”/”/>
<bean id=“accountRepository”
class=“app.impl.JdbcAccountRepository””/>
<bean id=“dataSource” class=“com.oracle.jdbc.pool.OracleDataSource””>
<property name=“URL” value=“jdbc:oracle:thin:@localhost:1521:BANK” />
<property name=“user” value=“moneytransfer-app” />
</bean>
</beans>
18
No need to specify
constructor-arg or
property
109
Ramkrishna IT Systems
Quick Start Summary
• Spring container needs POJOs and wiring
instructions to assemble your application
• Wiring instructions can be provided in XML…
• …but also using Java with @Bean-methods
• … or @Autowired annotations…
• …or a combination
110
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
111
Ramkrishna IT Systems
Configuration Annotations
•
•
•
•
•
•
@Autowired
@Qualifier / @Primary
@Resource
@Value
@Component / @Repository
Shown already:
– @Configuration / @Bean plus @Scope, @Import, etc.
– @PostConstruct / @PreDestroy / @Required
112
Ramkrishna IT Systems
@Autowired
• Asks Spring to autowire fields, methods or
constructors by using the type`
– Requires unique match!
• Removes the need to specify constructor-arg
or property elements in XML`
public class TransferServiceImpl implements TransferService
@Autowired
public TransferServiceImpl(AccountRepository ar) {
this.accountRepository = ar;
}
…
}
113
Ramkrishna IT Systems
@Autowired
• Methods can have any name
• Methods and constructors can have multiple
arguments that will all be injected
public class MyServiceImpl implements MyService
@Autowired
public void initialize(SomeDependency sd, OtherDependency od) {
this.someDependency = sd;
this.otherDependency = od;}
…
}
114
Ramkrishna IT Systems
Disambiguation with @Autowired
• Disambiguation needed when multiple beans of
same type exist, one of which must be injected
• Using @Qualifier you can inject beans by name
@Autowired
@Qualifier(“primaryDataSource”)
private DataSource dataSource;
@Autowired
void init(@Qualifier(“primaryDataSource”) DataSource primary,
@Qualifier(“altDataSource”) DataSource alternative)
{ … }
24
Specify name of
bean to inject
115
Ramkrishna IT Systems
Option-I use qualifier child element in <bean> definition
<bean class=“com.rits.SomeDBSource”>
<qualifier value=“primaryDataSource” >
</bean>
<bean class=“com.rits.SomeOtherDBSource”>
<qualifier value=“primaryDataSource” >
</bean>
116
Ramkrishna IT Systems 25
Disambiguation with @Primary
Option-II Java-based config alternative solution:
one bean can be made the primary candidate for
autowiring
– Will be used in case of multiple matches by type
@Bean @Primary
public DataSource standardDataSource() {
…
}
@Bean
public DataSource backupDataSource() {
…
}
117
Ramkrishna IT Systems
@Resource ("myBeanName")
•
•
•
•
JSR-250 annotation (not Spring-specific)
Injects a bean identified by the given name
Useful when auto wiring by type does not work
Can also lookup JNDI references
public class TransferServiceImpl implements TransferService {
@Resource("myBackupRepository")
public void setBackupRepo(AccountRepository repo) {
this.backRepo = repo;
}
}
26
Option-III
118
Ramkrishna IT Systems 27
@Resource in Spring
Some additional behavior over Java EE 5:
• By default, falls back to autowiring by type if no
bean with given name exists
• Works for all methods, not just setters
– But not for constructors!
119
Ramkrishna IT Systems 28
SpEL and Annotations
• Use @Value for SpEL expressions in Java code
– On a field or method or on parameter of autowired
method or constructor
@Value("#{ systemProperties['user.region'] }")
private String defaultLocale;
@Value("#{ systemProperties['user.region'] }")
public void setDefaultLocale(String defaultLocale) { … }
@Autowired
public void configure(AccountRepository accountRepository,
@Value("#{ systemProperties['user.region'] }") String defaultLocale) {
…
}
120
Ramkrishna IT Systems
<context:annotation-config/>
Turns on checking of DI
annotations for beans declared
in this context
<bean id=“transferService” class=“transfer.TransferService””/>
<bean id=“accountRepository” class=“transfer.JdbcAccountRepository””/>
</beans>
29
For these Annotations to
Work…
We need to ‘enable them’, just like for Java-based
configuration
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="...">
121
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
122
Ramkrishna IT Systems 31
@Component
• Identifies POJOs as Spring Beans
• Removes the need to specify almost anything in XML
@Component
public class TransferServiceImpl implements TransferService
@Autowired
public TransferServiceImpl(AccountRepository ar) {
this.accountRepository = ar;
}
…
}
123
Ramkrishna IT Systems 32
@Component and names
• Default bean name is de-capitalized non-qualified name
• @Component takes an optional String to name the bean
– Arguably not a best practice to put bean names in your Java
code
”)@Component(“transferService”)
public class TransferServiceImpl implements TransferService
@Autowired
public TransferServiceImpl(AccountRepository ar) {
this.accountRepository = ar;
}
…
}
124
Ramkrishna IT Systems 33
For This Annotation To Work…
• We need to enable ‘component scanning’
– Auto-enables <context:annotation-config/>
<beans xmlns="http://www.springframework.org/schema/beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package=“transfer””/>
</beans>
No more need to mention the
beans in the application context
125
Ramkrishna IT Systems 34
@Scope and @Primary
Like with @Bean:
• @Scope allows customizing the instantiation strategy
”)@Scope(“prototype”) @Component
public class TransferServiceImpl implements TransferService {
…
• @Primary allows making one component-scanned bean
the primary candidate for autowiring
@Primary @Component
public class DefaultCalculationService implements CalculationService {
…
126
Ramkrishna IT Systems 35
Scanning and auto-wiring for
@Configuration classes
• Are picked up by component scanning
– No more need for XML bean definition or @Import
• Can use autowiring
– Like any Spring-bean
– Gives access to external beans from @Bean methods
• Can be autowired into another @Configuration
– Allowing for external @Bean methods to be called
– Type-safe, IDE-friendly alternative to by-name wiring
127
Ramkrishna IT Systems 36
Combined Example
@Configuration
public class InfraConfig {
@Bean public DataSource dataSource() {
DataSource dataSource = ...;
return dataSource;
}
}
@Configuration @Import(InfraConfig.class)
public class RewardsConfig {
@Autowired InfraConfig infraConfig;
@Bean AccountRepository accountRepository() {
JdbcAccountRepository repository = new JdbcAccountRepository();
repository.setDataSource(infraConfig.dataSource());
return repository;
}
}
Import not needed if InfraConfig
was component-scanned
Alternative is to simply autowire
DataSource directly
128
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
129
Ramkrishna IT Systems 38
Stereotype annotations
• Component scanning also checks for annotations
that are themselves annotated with @Component
– So-called stereotype annotations(Marker annotaion suggesting specific purpose
– Identify the architectural purpose of a class
– Particularly useful for matching (e.g. with AOP)
• Spring framework stereotype annotations:
– @Service – identify service classes
– @Repository – identify data access classes
– @Controller – identify web presentation classes
• Other Spring-based frameworks define their own
130
Ramkrishna IT Systems 39
Meta-annotations
• A meta-annotation is an annotation which can be used to
annotate other annotations
• e.g. all of your service beans should be configurable using
component scanning and be transactional
@Transactional(timeout=60)
@Service
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyTransactionalService {
String value() default "";
}
@MyTransactionalService
public class TransferServiceImpl implements TransferService {
...
131
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
132
Ramkrishna IT Systems 41
When use what?
Annotations:
• Nice for frequently changing beans
– Start using for small isolated parts of your application
(e.g. Spring @MVC controllers)
• Pros:
– Single place to edit (just the class)
– Allows for very rapid development
• Cons:
– Configuration spread across your code base
– Only works for your own code
--Maintenance issues
--Recompilation for any changes
133
Ramkrishna IT Systems
When use what?
XML:
• Cons:
– Some people just don't like XML...
• For infrastructure and more 'static' beans
• Pros:
– Is centralized in one (or a few) places
– Most familiar configuration format for most people
– Can be used for all classes (not just your own)
134
Ramkrishna IT Systems 43
When use what?
Java-based:
• For full control over instantiation and
configuration
– As alternative to implementing FactoryBean
• Pros:
– Configuration still external to code
– Integrates well with legacy code
• Can call methods such as addDataSource(DataSource d)
• Cons:
– Wiring won't show up in STS
– No equivalent to the XML namespaces
135
Ramkrishna IT Systems
Topics in this Session
•
•
•
•
•
•
•
•
•
Configuration Approaches
Java-based Configuration
Annotation Quick Start
Other Configuration Annotations
Component Scanning
Stereotype and Meta-annotations
When To Use What
Summary & Lab
Advanced Options
136
Ramkrishna IT Systems 45
Summary
• Spring’s configuration directives can be written
in XML, using Java or using annotations
• You can mix and match XML, Java and
annotations as you please
• Autowiring with @Component or @Configuration
allows for almost empty XML configuration files
137
Ramkrishna IT Systems
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
LAB
Using Spring’s annotations to Configure and
test an application
138
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming
Cross-Cutting Concerns : Transactions, Logging, Security, Caching,
ErrorHandling
Goal :
Separation of cross-cutting concerns from business logic
Write common functionality at one place
Declaratively add the functionality in the code
Decoupling business domain logic from infrastructure code
No impact on adding or removing the infra functionality.
139
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming
Cross-Cutting Concerns : Transactions, Logging, Security, Caching,
ErrorHandling
Goal :
Separation of cross-cutting concerns from business logic
Write common functionality at one place
Declaratively add the functionality in the code
Decoupling business domain logic from infrastructure code
No impact on domain code while adding/removing the infra.
140
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming
Goal :
To Avoid Code Tangling(Mixing of concerns)
To avoid Code scattering(Duplication of code at multiple places)
141
Ramkrishna IT Systems 6
Implementing Cross Cutting
Concerns Without Modularization
• Failing to modularize cross-cutting concerns
leads to two things
1. Code tangling
• A coupling of concerns
2. Code scattering
• The same concern spread across modules
142
Ramkrishna IT Systems 7
Symptom #1: Tangling
public class RewardNetworkImpl implements RewardNetwork {
public RewardConfirmation rewardAccountFor(Dining dining) {
if (!hasPermission(SecurityContext.getPrincipal()) {
throw new AccessDeniedException();
}
Account a = accountRepository.findByCreditCard(…
Restaurant r = restaurantRepository.findByMerchantNumber(…
MonetaryAmount amt = r.calculateBenefitFor(account, dining);
…
}
}
Mixed Concerns
143
Ramkrishna IT Systems
Duplication
8
Symptom #2: Scattering
public class HibernateAccountManager implements AccountManager {
public Account getAccountForEditing(Long id) {
if (!hasPermission(SecurityContext.getPrincipal()) {
throw new AccessDeniedException();
}
…
public class HibernateMerchantReportingService implements
MerchantReportingService {
public List<DiningSummary> findDinings(String merchantNumber,
DateInterval interval) {
if (!hasPermission(SecurityContext.getPrincipal()) {
throw new AccessDeniedException();
}
…
144
Ramkrishna IT Systems
BankService
System Evolution Without
Modularization
Code
tangling
Security
Transactions
Logging
CustomerService ReportingService
Code
scattering
145
Ramkrishna IT Systems
How AOP Works
1. Implement your mainline application logic
Focusing on the core problem
2. Write aspects to implement your cross-cutting
concerns
Spring provides many aspects out-of-the-box
3. Weave the aspects into your application
Adding the cross-cutting behaviours to the right
places
146
Ramkrishna IT Systems
System Evolution: AOP based
BankService
Security
Aspect
CustomerService
Transaction
Aspect
ReportingService
Logging
Aspect
147
Ramkrishna IT Systems 13
Leading AOP Technologies
• AspectJ
– Original AOP technology (first version in 1995)
– Offers a full-blown Aspect Oriented Programming
language
• Uses byte code modification for aspect weaving
• Spring AOP
– Java-based AOP framework with AspectJ integration
• Uses dynamic proxies for aspect weaving
– Focuses on using AOP to solve enterprise problems
– The focus of this session
148
Ramkrishna IT Systems 14
Topics in this session
•
•
•
•
•
•
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
– Named Pointcuts
– Context selecting pointcuts
– Working with annotations
149
Ramkrishna IT Systems
Core AOP Concepts
•Aspect Oriented Programming : Terminology
Advice :
A piece of code that needs to be executed before/after/around
business logic. This code executes without knowledge of domain code.
What and when is defined by advice
Should it be applied before the method (Before advice)
Should it be applied after method execution (After-return advice)
Should it be applied before and after method (Around advice)
Should it be applied if method throws an exception(After-throwing)
Should it be applied after method execution (even if method throws
exception) (After advice)
150
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming : Terminology
JoinPoint :
• A join-point is a point in the execution of application where a
particular cross-cutting concern (advice) is to be plugged-in
• A JoinPoint could be a method invocation, a change of a field value
or it could be an exception being thrown
• Spring only supports method invocation as a JoinPoint
151
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming : Terminology
PointCut :
• Its an expression which decides the set of JoinPoints where the
advice is to applied.
•Advices define when and what is to be applied while PointCut defines
where it is to be applied.
•PointCuts in Spring define set of methods using regular expressions.
152
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming : Terminology
•Aspect :
• Aspect is combination of JoinPoints and PointCuts and advice
Introduction :
• It allows you to add new methods or attributes to existing classes
without changing them
153
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming : Terminology
•Target :
• Object on which advice is to applied
Proxy :
• A new Object which wraps the target object and intercepts the calls
from the Client.
•Proxy is the Object which will be created at runtime and it intercepts
the invocations.
154
Ramkrishna IT Systems
AOP
•Aspect Oriented Programming : Terminology
•Weaving :
• Process of applying aspects on target objects
•Weaving in Spring happens at runtime
Proxy :
• A new Object which wraps the target object and intercepts the calls
from the Client.
•Proxy is the Object which will be created at runtime and it intercepts
the invocations.
155
Ramkrishna IT Systems
Steps to Use AOP
1. Implement your mainline application logic
Focusing on the core problem
2. Write aspects to implement your cross-cutting
concerns
•
Spring provides many aspects out-of-the-box
3. Weave the aspects into your application
•
Adding the cross-cutting behaviours to the right
places
156
Ramkrishna IT Systems
AOP Quick Start
• Consider this basic requirement
• How can you use AOP to meet it?
Log a message every time a property is about to change
157
Ramkrishna IT Systems
Target Object :
Whose State Change is to be tracked
public class SimpleCache implements Cache {
private int cacheSize;
private DataSource dataSource;
private String name;
public void setCacheSize(int size) { cacheSize = size; }
public void setDataSource(DataSource ds) { dataSource = ds; }
public void setBeanName(String beanName) { name = beanName; }
public String toString() { return name; }
…
}
158
Ramkrishna IT Systems
Implement the Aspect
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
@Before(“execution(void set*(*))”)
public void trackChange() {
logger.info(“Property about to change…”);
}
}
159
Ramkrishna IT Systems
<beans>
<aop:aspectj-autoproxy>
<aop:include name=“propertyChangeTracker” />
</aop:aspectj-autoproxy>
<bean id=“propertyChangeTracker” class=“example.PropertyChangeTracker” />
</beans>
20
Configures Spring to apply the
@Aspect to your beans
Configure the Aspect as a
Bean
aspects-config.xml
160
Ramkrishna IT Systems
Include the Aspect
Configuration
<beans>
<import resource= “aspects-config.xml”/>
<bean name=“cache-A” class=“example.SimpleCache” ../>
<bean name=“cache-B” class=“example.SimpleCache” ../>
<bean name=“cache-C” class=“example.SimpleCache” ../>
</beans>
application-config.xml
161
Ramkrishna IT Systems
Test the Application
ApplicationContext context =
new ClassPathXmlApplicationContext(“application-config.xml”);
Cache cache = (Cache) context.getBean(“cache-A”);
cache.setCacheSize(2500);
INFO: Property about to change…
162
Ramkrishna IT Systems
SimpleCache
(target)
PropertyChange
Tracker (aspect)
4. Matching advice is executed
1. Spring creates a proxy that brings
the aspect and target together
23
3. All calls routed through proxy
Spring AOP Proxy (this)
<<interface>>
Cache
the business interface
of the target
How Aspects are Applied
2. The proxy implements
setCacheSize(2500)
163
Ramkrishna IT Systems
}
}
Tracking Property Changes –
With Context
• Context is provided by the JoinPoint method
parameter
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
Context about the intercepted point
@Before(“execution(void set*(*))”)
public void trackChange(JoinPoint point) {
String name = point.getSignature().getName();
Object newValue = point.getArgs()[0];
logger.info(name + “ about to change to ” + newValue +
“ on ” + point.getTarget());
INFO: setCacheSize about to change to 2500 on cache-A
164
Ramkrishna IT Systems
Topics in this session
•
•
•
•
•
•
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
– Named Pointcuts
– Context selecting pointcuts
– Working with annotations
165
Ramkrishna IT Systems
Defining Pointcuts
• With Spring AOP you write pointcuts using
AspectJ’s pointcut expression language
– For selecting where to apply advice
• Complete expression language reference
available at
– http://www.eclipse.org/aspectj
166
Ramkrishna IT Systems
Common Pointcut Designator
• execution(<method pattern>)
– The method must match the pattern
• Can chain together to create composite
pointcuts
– && (and), || (or), ! (not)
– [Modifiers] ReturnType [ClassType]
MethodName ([Arguments]) [throws ExceptionType]
167
Ramkrishna IT Systems
Writing expressions
execution(* rewards.restaurant.*Service.find*(..))
package
type params
methoddesignator
return type
168
Ramkrishna IT Systems 29
Execution Expression
Examples
execution(void send*(String))
– Any method starting with send that takes a single String
parameter and has a void return type
execution(* send(*))
– Any method named send that takes a single parameter
execution(* send(int, ..))
– Any method named send whose first parameter is an int (the
“..” signifies 0 or more parameters may follow)
169
Ramkrishna IT Systems 30
Execution Expression
Examples
execution(void example.MessageServiceImpl.*(..))
– Any visible void method in the MessageServiceImpl class
execution(void example.MessageService+.send(*))
– Any void method named send in any object of type
MessageService (that include possible child classes or
implementors of MessageService)
execution(@javax.annotation.security.RolesAllowed void send*(..))
– Any void method starting with send that is annotated with
the @RolesAllowed annotation
170
Ramkrishna IT Systems 31
Execution Expression Examples
working with packages
execution(* rewards.*.restaurant.*.*(..))
– There is one directory between rewards and restaurant
execution(* rewards..restaurant.*.*(..))
– There may be several directories between rewards and
restaurant
execution(* *..restaurant.*.*(..))
– Any sub-package called restaurant
171
Ramkrishna IT Systems
Proxy BeforeAdvice Target
Before Advice
172
Ramkrishna IT Systems
Before Advice Example
• Use @Before annotation
– If the advice throws an exception, target will not be
called
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
@Before(“execution(void set*(*))”)
public void trackChange() {
logger.info(“Property about to change…”);
}
}
Track calls to all setter methods
173
Ramkrishna IT Systems
After Advice
Proxy AfterReturning Target
Successful return
174
Ramkrishna IT Systems
After Returning
• @Aspect
• public class PropertyChangeTracker {
• @Pointcut(" execution(* update*(..)) || execution(* set*(..))")
• void updateORSetMethod(){}
• @Pointcut("(!execution(* bank.server.internal.BankImpl.get*(*))) && execution(*
get*(..))")
• void getMethodAdvice(){}
• @After("updateORSetMethod()")
• void trackChange2(JoinPoint jp){
• String methodName = jp.getSignature().getName();
• Object newValue = jp.getArgs()[0];
• System.out.println("After Advice of PropertyChangeTracker1 invoked for method
"+methodName);
• System.out.println("After 1 Property changed to "+newValue);
• }
• }
175
Ramkrishna IT Systems
After Advice
Proxy After Advice Target
Success or Exception
176
Ramkrishna IT Systems
AfterThrowing Advice
Proxy After Advice Target
Exception
177
Ramkrishna IT Systems
After Throwing
• @Aspect
• public class PropertyChangeTracker {
• @Pointcut(" execution(* update*(..)) || execution(* set*(..))")
• void updateORSetMethod(){}
• @Pointcut("(!execution(* bank.server.internal.BankImpl.get*(*))) && execution(*
get*(..))")
• void getMethodAdvice(){}
• @After("updateORSetMethod()")
• @AfterThrowing(value="getMethodAdvice()",throwing="e")
• void handleException(JoinPoint p, Throwable e){
• System.out.println("DEBUG AfterThrowing invoked due ot Exception
"+e.getMessage()+"By method "+p.getSignature().getName()+" On Class
"+p.getTarget().getClass().getName());
• }
• }
178
Ramkrishna IT Systems
Around Advice
Around TargetProxyProxy Around Target
proceed()
Around Advice
179
Ramkrishna IT Systems
@Around
• @Aspect
• public class PropertyChangeTracker {
• @Around("! execution(* bank.server.internal.BankImpl.get*(*)) && (execution(*
update*(..)) || execution(* set*(..))|| execution(* get*(..)))" )
• Object trackChange(ProceedingJoinPoint jp) throws Throwable{
– String methodName = jp.getSignature().getName();
• Object newValue =null;
– if(jp.getArgs().length>0){
– newValue = jp.getArgs()[0];
– }
– System.out.println("Kind ="+jp.getKind());
– System.out.println("PropertyChangeTracker FIRST invoked for method "+methodName);
– System.out.println("BEFORE Property Change About to change to "+newValue);
– Object value = jp.proceed();
– System.out.println("AROUND AFTER property change is complete value ="+value);
– if(value instanceof String)
– return value+"CHANGED BY ADVICE";
– return value;
• }}
}
180
Ramkrishna IT Systems
LAB
181
Ramkrishna IT Systems 44
Alternative Spring AOP
Syntax - XML
• Annotation syntax is Java 5+ only
• XML syntax works on Java 1.4
• Approach
– Aspect logic defined Java
– Aspect configuration in XML
• Uses the aop namespace
182
Ramkrishna IT Systems 45
Tracking Property Changes -
Java Code
public class PropertyChangeTracker {
public void trackChange(JoinPoint point) {
…
}
}
Aspect is a Plain Java Class with no Java 5 annotations
183
Ramkrishna IT Systems 46
Tracking Property Changes -
XML Configuration
<aop:config>
<aop:aspect ref=“propertyChangeTracker”>
<aop:before pointcut=“execution(void set*(*))” method=“trackChange”/>
</aop:aspect>
</aop:config>
<bean id=“propertyChangeTracker” class=“example.PropertyChangeTracker” />
• XML configuration uses the aop namespace
184
Ramkrishna IT Systems 48
Topics in this session
•
•
•
•
•
•
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
–
–
–
–
Named Pointcuts
Context selecting pointcuts
Working with annotations
Limitations of Spring AOP
185
Ramkrishna IT Systems 49
• Allow to reuse and combine pointcuts
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
@Before(“serviceMethod() || repositoryMethod()”)
public void monitor() {
logger.info(“A business method has been accessed…”);
}
@Pointcut(“execution(* rewards.service..*Service.*(..))”)
public void serviceMethod() {}
@Pointcut(“execution(* rewards.repository..*Repository.*(..))”)
public void repositoryMethod() {}
}
Named pointcuts
186
Ramkrishna IT Systems
}
}
Named pointcuts
• Expressions can be externalized
public class SystemArchitecture {
@Pointcut(“execution(* rewards.service..*Service.*(..))”)
public void serviceMethods() {}
}
@Aspect
public class ServiceMethodInvocationMonitor {
private Logger logger = Logger.getLogger(getClass());
@Before(“com.acme.SystemArchitecture.serviceMethods()” )
public void monitor() {
logger.info(“A service method has been accessed…”);
Fully-qualified pointcut name
50
187
Ramkrishna IT Systems 51
• Give the possibility to break one complicated
expression into several sub-expressions
• Allow pointcut expression reusability
• Best practice: consider externalizing expressions
into one dedicated class
– When working with many pointcuts
– When writing complicated expressions
Named pointcuts - Summary
188
Ramkrishna IT Systems 52
Topics in this session
•
•
•
•
•
•
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
–
–
–
–
Named Pointcuts
Context selecting pointcuts
Working with annotations
Limitations of Spring AOP
189
Ramkrishna IT Systems
Context Selecting Pointcuts
• Pointcuts may also select useful join point
context
–
–
–
–
The currently executing object (proxy)
The target object
Method arguments
Annotations associated with the method, target, or
arguments
• Allows for simple POJO advice methods
– Alternative to working with a JoinPoint object directly
53
190
Ramkrishna IT Systems
Context Selecting Example
• Consider this basic requirement
Log a message every time Server is about to start
public interface Server {
public void start(Map input);
public void stop();
}
In the advice, how do we access Server? Map?
54
191
Ramkrishna IT Systems 55
Without context selection
@Before(“execution(void example.Server+.start(java.util.Map))”)
public void logServerStartup(JoinPoint jp) {
Server server = (Server) jp.getTarget();
Object[] args= jp.getArgs();
Map map = (Map) args[0];
…
}
• All needed info must be obtained from the
JoinPoint object
192
Ramkrishna IT Systems 56
With context selection
@Before(“execution(void example.Server+.start(java.util.Map))
&& target(server) && args(input)”)
public void logServerStartup(Server server, Map input) {
…
}
• Best practice: use context selection
– Method attributes are bound automatically
- target(server) selects the target of the execution (your object)
- this(server) would have selected the proxy
193
Ramkrishna IT Systems
Context Selection - Named
Pointcut
@Before(“serverStartMethod(server, input)”)
public void logServerStartup(Server server, Map input) {
…
}
@Pointcut(“execution(void example.Server+.start(java.util.Map))
&& target(server) && args(input)”)
public void serverStartMethod (Server server, Map input) {}
57
‘target’ binds the server starting up ‘args’ binds the argument value
194
Ramkrishna IT Systems 58
Topics in this session
•
•
•
•
•
•
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
–
–
–
–
Named Pointcuts
Context selecting pointcuts
Working with annotations
Limitations of Spring AOP
195
Ramkrishna IT Systems 59
Pointcut expression examples
using annotations
• execution(
@org.springframework.transaction.annotation.Transactional
void *(..))
– Any method marked with the @Transactional
annotation
• execution( (@example.Tracked *) *(..))
– Any method that returns a value marked with the
@Tracked annotation
196
Ramkrishna IT Systems
@Secured(allowedRoles={“teller”,”manager”})
public void waiveFee () {
…
}
60
Example
Requirements:
Run a security check before any @Secured service operation
Security logic depends on:
∉
∉
∉
annotation attribute value – what roles to check?
method name – what method is protected?
the ‘this’ object – Spring AOP proxy being protected
197
Ramkrishna IT Systems 61
AOP and annotations - Example
@Before(“execution(* service..*.*(..)) && target(object) &&
@annotation(secured)””))
public void runCheck(JoinPoint jp, Object object, Secured secured) {
checkPermission(jp, object, secured.allowedRoles());
}
Run a security check before any @Secured service operation
• Use of the annotation() designator
198
Ramkrishna IT Systems 62
AOP and annotations
– Named pointcuts
@Before(“securedMethod(object, secured)””)
public void runCheck(JoinPoint jp, Object object, Secured secured) {
checkPermission(jp, object, secured.allowedRoles());
}
@Pointcut((“execution(* service..*.*(..)) && target(object) &&
@annotation(secured)””))
public void securedMethod(Object object, Secured secured) {}
Run a security check before any @Secured service operation
199
Ramkrishna IT Systems 63
Topics in this session
•
•
•
•
•
•
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
–
–
–
–
Named Pointcuts
Context selecting pointcuts
Working with annotations
Limitations of Spring AOP
200
Ramkrishna IT Systems 64
Limitations of Spring AOP
• Can only advise public Join Points
• Can only apply aspects to Spring beans
• Some limitations of weaving with proxies
– Spring will add behavior using dynamic proxies if a
Join Point is declared on an interface
– If a Join Point is in a class without an interface,
Spring will revert to using CGLIB for weaving
– When using proxies, if method a() calls method b()
on the same class/interface, advice will never be
executed for method b()
201
Ramkrishna IT Systems 65
Summary
• Aspect Oriented Programming (AOP)
modularizes cross-cutting concerns
• An aspect is a module containing cross-
cutting behavior
– Behavior is implemented as “advice”
– Pointcuts select where advice applies
– Five advice types: Before, AfterThrowing,
AfterReturning, After and Around
• Aspects are defined in Java with
annotations or XML configuration
202
Ramkrishna IT Systems 48
LAB : Advance AOP
203
Ramkrishna IT Systems
Data Access Using Spring
• Resource Management :
– Creating Connection Pools
– Acquiring and releasing connections from/to the pool
– Closing connections
– Demarcation of transaction
– Commit or rollback of transaction
– Iterating through ResultSet and creating JavaObjects
– Checking ErrorCodes and mapping exceptions to meaningful messages
– Checking Exception state and mapping it to meaningful messages
All the concerns listed above is a job of application developer.
Spring takes it away from developer.
204
Ramkrishna IT Systems
Not Effective - Copy &
Pasting Code
doSomeWork(...) {
try {
get connection
begin transaction
execute SQL
process the result set
commit
}
catch (SQLException e) {
rollback
}throw application exception
} finally {
try {
close connection
}
catch {}
}
Unique
Copied
around
everywhere
205
Ramkrishna IT Systems
Spring Features for resource Management
• Declarative transaction management
– Transactional boundaries declared via configuration
– Enforced by a Spring transaction manager
• Automatic connection management
– Connections acquired/released automatically
– No possibility of resource leak
• Intelligent exception handling
– Root cause failures always reported
– Resources always released properly
206
Ramkrishna IT Systems
Spring Resource
Management
doSomeWork(..) {
try {
establish connection
begin transaction
execute SQL
process the result set
commit
}
catch (SQLException) {
rollback
throw application exception
} finally {
try {
close connection
}
catch {}
}
BEFORE
207
Ramkrishna IT Systems
After
Spring Resource
Management
@Transactional
doSomeWork(..) {
execute SQL
process the result set
}
208
Ramkrishna IT Systems
Spring Resource Management
Works Everywhere
• Works consistently with all leading data access
technologies
–
–
–
–
–
Java Database Connectivity (JDBC)
JBoss Hibernate
Java Persistence API (JPA)
EclipseLink
Apache iBatis
• In any environment
– Local (standalone app, web app)
– Full-blown JEE container
17
209
Ramkrishna IT Systems
Service Repository
TransactionManager DataSource Connection
(input)
findDomainObject(criteria)
select data
domainObject
mapObject(ResultSet)
get connection
new
begin transaction
transaction
A Typical Application invocation sequence
210
Ramkrishna IT Systems
Declarative Transaction
Management
• Spring adds the transaction management calls
around your service logic
• You simply declare the transactional policies and
Spring enforces them
211
Ramkrishna IT Systems
Setting Transactional Policies
Declaratively
public void invoke(…) {
// your application logic
}
}
Tells Spring to always run this method
in a database transaction
public class ServiceImpl implements ServiceInterface {
@Transactional
212
Ramkrishna IT Systems
Spring
TransactionInterceptor
begin commit
TransactionManager
ServiceImpl
Transaction
management
behavior is added
around your code
invoke(input)
You can change
transaction
managers without
affecting your
Application Code
Enforcing Declarative
Transactional Policies
Spring AOP Proxy
213
Ramkrishna IT Systems
Effects on Connection
Management
• Connections are managed for you
– Driven by transactional boundaries
– Not the responsibility of application code
– No possibility of connection leak
• Repositories always use the transactional
connection for data access
– Spring provides several ways to ensure this
214
Ramkrishna IT Systems
Local Hibernate Configuration
RewardNetworkImpl
Hibernate
AccountRepository
Hibernate
RestaurantRepository JdbcRewardRepository
SessionFactory
Hibernate
TransactionManager
BasicDataSource
LocalSession
FactoryBean
creates
215
Ramkrishna IT Systems
Introduction to Spring JDBC
Simplifying JDBC-based data access with Spring
JDBC
216
Ramkrishna IT Systems
Topics in this Session
• Problems with traditional JDBC
– Results in redundant, error prone code
– Leads to poor exception handling
• Spring’s JdbcTemplate
Configuration
Query execution
Working with result sets
Exception handling
• JDBC Namespace
2
217
Ramkrishna IT Systems
Redundant, Error Prone Code
public List findByLastName(String lastName) {
List personList = new ArrayList();
Connection conn = null;
String sql = “select first_name, age from PERSON where last_name=?“;
try {
DataSource dataSource = DataSourceUtils.getDataSource();
conn = dataSource.getConnection();
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String firstName = rs.getString(”first_name“);
int age = rs.getInt(“age”);
personList.add(new Person(firstName, lastName, age));
} catch (SQLException e) { /* ??? */ }
finally {
conn.close();
} catch (SQLException e) { /* ??? */ }
return personList;
218
Ramkrishna IT Systems
Redundant, Error Prone Code
public List findByLastName(String lastName) {
List personList = new ArrayList();
Connection conn = null;
String sql = "select first_name, age from PERSON where last_name=?";
try {
DataSource dataSource = DataSourceUtils.getDataSource();
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, lastName);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String firstName = rs.getString(“first_name”);
int age = rs.getInt(“age”);
personList.add(new Person(firstName, lastName, age));
}
} catch (SQLException e) { /* ??? */ }
finally {
try {
conn.close();
} catch (SQLException e) { /* ??? */ }
}
return personList;
}
4
The bold matters - the
rest is boilerplate
219
Ramkrishna IT Systems
Exception Handling is poor
public List findByLastName(String lastName) {
List personList = new ArrayList();
Connection conn = null;
String sql = “select first_name, age from PERSON where last_name=?“;
try {
DataSource dataSource = DataSourceUtils.getDataSource();
conn = dataSource.getConnection();
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String firstName = rs.getString(”first_name“);
int age = rs.getInt(“age”);
personList.add(new Person(firstName, lastName, age));
} catch (SQLException e) { /* ??? */ }
finally {
conn.close();
} catch (SQLException e) { /* ??? */ }
return personList;
What can we do?
220
Ramkrishna IT Systems
Spring’s JdbcTemplate
• Greatly simplifies use of the JDBC API
– Eliminates repetitive boilerplate code
– Alleviates common causes of bugs
– Handles SQLExceptions properly
• Without sacrificing power
– Provides full access to the standard JDBC constructs
221
Ramkrishna IT Systems
Acquisition of the connection
Participation in the transaction
Execution of the statement
Processing of the result set
Handling any exceptions
Release of the connection
JdbcTemplate in a Nutshell
int count = jdbcTemplate.queryForInt(
“SELECT COUNT(*) FROM CUSTOMER””);
All handled
by Spring
222
Ramkrishna IT Systems
Creating a JdbcTemplate
• Requires a DataSource
• Create a template once and re-use it
– Do not create one for each use
– Thread safe after construction
JdbcTemplate template = new JdbcTemplate(dataSource);
223
Ramkrishna IT Systems
When to use JdbcTemplate
• Useful standalone
– Anytime JDBC is needed
– In utility or test code
– To clean up messy legacy code
• Useful for implementing a repository in
a layered application
– Also known as a data access object (DAO)
224
Ramkrishna IT Systems
Implementing a JDBC-based
Repository
public class AccountRepositoryImpl implements AccountRepository {
private JdbcTemplate jdbcTemplate;
public AccountRepositoryImpl (JdbcTemplate template) {
public int getAccountCount() {
String sql = “select count(*) from Accounts”;
return jdbcTemplate.queryForInt(sql);
}
this.jdbcTemplate = template;
}
DI in config file
225
Ramkrishna IT Systems
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${oracleDriver}" />
<property name="url" value="${oracleURL}" />
<property name="username" value="${oracleUser}" />
<property name="password" value="${oraclePassword}"></property>
</bean>
<bean class="bank.server.internal.AccountRepositoryImpl" >
<constructor-arg name="dataSource" ref="dataSource" />
<constructor-arg name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<constructor-arg name="dataSource" ref="dataSource" />
</bean>
JdbcTemplate Mapping in Config File
226
Ramkrishna IT Systems
Querying with JdbcTemplate
• JdbcTemplate can query for
– types (int, long, String)
– Generic Maps
– Domain Objects
227
Ramkrishna IT Systems
Querying for Simple Java
Types (1)
• Query with no bind variables
public int getPersonCount() {
String sql = “select count(*) from PERSON”;
return jdbcTemplate.queryForInt(sql);
228
Ramkrishna IT Systems
Querying With JdbcTemplate
• Query with a bind variable
– Note the use of a variable argument list
private JdbcTemplate jdbcTemplate;
public int getCountOfPersonsOlderThan(int age) {
return jdbcTemplate.queryForInt(
“select count(*) from PERSON where age > ?”, age);
No need for new Object[] { new Integer(age) }
229
Ramkrishna IT Systems
Generic Queries
• JdbcTemplate can return each row of a ResultSet
as a Map
• When expecting a single row
– Use queryForMap(..)
• When expecting multiple rows
– Use queryForList(..)
• Useful for reporting, testing
230
Ramkrishna IT Systems
Querying for Generic Maps
(1)
• Query for a single row
• returns:
Map { ID=1, FIRST_NAME=“John”, LAST_NAME=“Doe” }
public Map getPersonInfo(int id) {
String sql = “select * from PERSON where id=?”;
return jdbcTemplate.queryForMap(sql, id);
}
A Map of [Column Name | Field Value ] pairs
231
Ramkrishna IT Systems
Querying for Generic Maps
(2)
• Query for multiple rows
• returns:
List {
0 - Map { ID=1, FIRST_NAME=“Vivek”, LAST_NAME=“Kulkarni” }
1 - Map { ID=2, FIRST_NAME=“Ram”, LAST_NAME=“Joshi” }
2 - Map { ID=3, FIRST_NAME=“Subhash”, LAST_NAME=“Bose” }
}
public List getAllPersonInfo() {
String sql = “select * from PERSON”;
return jdbcTemplate.queryForList(sql);
A List of Maps of [Column Name | Field Value ] pairs
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0
3.0

More Related Content

What's hot

Jira sync spec-en_2v0
Jira sync spec-en_2v0Jira sync spec-en_2v0
Jira sync spec-en_2v0Onlio
 
Oracle Distributed Document Capture
Oracle Distributed Document CaptureOracle Distributed Document Capture
Oracle Distributed Document Captureguest035a27
 
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...Lucas Jellema
 
Msbi online training
Msbi online trainingMsbi online training
Msbi online trainingDivya Shree
 
IDC Multicloud 2019 - Conference Milano , Oracle speech
IDC Multicloud 2019 - Conference Milano , Oracle speechIDC Multicloud 2019 - Conference Milano , Oracle speech
IDC Multicloud 2019 - Conference Milano , Oracle speechRiccardo Romani
 
Informatica Powercenter Architecture
Informatica Powercenter ArchitectureInformatica Powercenter Architecture
Informatica Powercenter ArchitectureBigClasses Com
 
ZK MVVM, Spring & JPA On Two PaaS Clouds
ZK MVVM, Spring & JPA On Two PaaS CloudsZK MVVM, Spring & JPA On Two PaaS Clouds
ZK MVVM, Spring & JPA On Two PaaS CloudsSimon Massey
 
Microsoft SQL Server - Parallel Data Warehouse Presentation
Microsoft SQL Server - Parallel Data Warehouse PresentationMicrosoft SQL Server - Parallel Data Warehouse Presentation
Microsoft SQL Server - Parallel Data Warehouse PresentationMicrosoft Private Cloud
 
Ibm xamarin gtruty
Ibm xamarin gtrutyIbm xamarin gtruty
Ibm xamarin gtrutyRon Favali
 
VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...
VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...
VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...VMworld
 
Be05 introduction to sql azure
Be05   introduction to sql azureBe05   introduction to sql azure
Be05 introduction to sql azureDotNetCampus
 
Study Notes - Event-Driven Data Management for Microservices
Study Notes - Event-Driven Data Management for MicroservicesStudy Notes - Event-Driven Data Management for Microservices
Study Notes - Event-Driven Data Management for MicroservicesRick Hwang
 
The State of Log Management & Analytics for AWS
The State of Log Management & Analytics for AWSThe State of Log Management & Analytics for AWS
The State of Log Management & Analytics for AWSTrevor Parsons
 
Microservices, DevOps & SRE
Microservices, DevOps & SREMicroservices, DevOps & SRE
Microservices, DevOps & SREAraf Karsh Hamid
 
Technology choices for Apache Kafka and Change Data Capture
Technology choices for Apache Kafka and Change Data CaptureTechnology choices for Apache Kafka and Change Data Capture
Technology choices for Apache Kafka and Change Data CaptureAndrew Schofield
 
Splunk for ITOps
Splunk for ITOpsSplunk for ITOps
Splunk for ITOpsSplunk
 
Oracle data integrator training from hyderabad
Oracle data integrator training from hyderabadOracle data integrator training from hyderabad
Oracle data integrator training from hyderabadFuturePoint Technologies
 
Introduction to Java Cloud Service
Introduction to Java Cloud ServiceIntroduction to Java Cloud Service
Introduction to Java Cloud ServicePerficient, Inc.
 
Siebel Resume Arquitecture
Siebel Resume ArquitectureSiebel Resume Arquitecture
Siebel Resume ArquitectureJose Martinez
 

What's hot (19)

Jira sync spec-en_2v0
Jira sync spec-en_2v0Jira sync spec-en_2v0
Jira sync spec-en_2v0
 
Oracle Distributed Document Capture
Oracle Distributed Document CaptureOracle Distributed Document Capture
Oracle Distributed Document Capture
 
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
 
Msbi online training
Msbi online trainingMsbi online training
Msbi online training
 
IDC Multicloud 2019 - Conference Milano , Oracle speech
IDC Multicloud 2019 - Conference Milano , Oracle speechIDC Multicloud 2019 - Conference Milano , Oracle speech
IDC Multicloud 2019 - Conference Milano , Oracle speech
 
Informatica Powercenter Architecture
Informatica Powercenter ArchitectureInformatica Powercenter Architecture
Informatica Powercenter Architecture
 
ZK MVVM, Spring & JPA On Two PaaS Clouds
ZK MVVM, Spring & JPA On Two PaaS CloudsZK MVVM, Spring & JPA On Two PaaS Clouds
ZK MVVM, Spring & JPA On Two PaaS Clouds
 
Microsoft SQL Server - Parallel Data Warehouse Presentation
Microsoft SQL Server - Parallel Data Warehouse PresentationMicrosoft SQL Server - Parallel Data Warehouse Presentation
Microsoft SQL Server - Parallel Data Warehouse Presentation
 
Ibm xamarin gtruty
Ibm xamarin gtrutyIbm xamarin gtruty
Ibm xamarin gtruty
 
VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...
VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...
VMworld 2013: Moving Enterprise Application Dev/Test to VMware’s Internal Pri...
 
Be05 introduction to sql azure
Be05   introduction to sql azureBe05   introduction to sql azure
Be05 introduction to sql azure
 
Study Notes - Event-Driven Data Management for Microservices
Study Notes - Event-Driven Data Management for MicroservicesStudy Notes - Event-Driven Data Management for Microservices
Study Notes - Event-Driven Data Management for Microservices
 
The State of Log Management & Analytics for AWS
The State of Log Management & Analytics for AWSThe State of Log Management & Analytics for AWS
The State of Log Management & Analytics for AWS
 
Microservices, DevOps & SRE
Microservices, DevOps & SREMicroservices, DevOps & SRE
Microservices, DevOps & SRE
 
Technology choices for Apache Kafka and Change Data Capture
Technology choices for Apache Kafka and Change Data CaptureTechnology choices for Apache Kafka and Change Data Capture
Technology choices for Apache Kafka and Change Data Capture
 
Splunk for ITOps
Splunk for ITOpsSplunk for ITOps
Splunk for ITOps
 
Oracle data integrator training from hyderabad
Oracle data integrator training from hyderabadOracle data integrator training from hyderabad
Oracle data integrator training from hyderabad
 
Introduction to Java Cloud Service
Introduction to Java Cloud ServiceIntroduction to Java Cloud Service
Introduction to Java Cloud Service
 
Siebel Resume Arquitecture
Siebel Resume ArquitectureSiebel Resume Arquitecture
Siebel Resume Arquitecture
 

Viewers also liked (16)

Resume_SurajitB
Resume_SurajitBResume_SurajitB
Resume_SurajitB
 
Log splitters
Log splittersLog splitters
Log splitters
 
Gentry christopher 4.4
Gentry christopher 4.4Gentry christopher 4.4
Gentry christopher 4.4
 
Panimoalassa on potentiaalia
Panimoalassa on potentiaaliaPanimoalassa on potentiaalia
Panimoalassa on potentiaalia
 
Karate Lessons Pelham
Karate Lessons PelhamKarate Lessons Pelham
Karate Lessons Pelham
 
The European soft drinks industry and balanced lifestyles
The European soft drinks industry and balanced lifestylesThe European soft drinks industry and balanced lifestyles
The European soft drinks industry and balanced lifestyles
 
Tree.one
Tree.oneTree.one
Tree.one
 
Fundusze europejskie 2014 - 2020
Fundusze europejskie 2014 - 2020Fundusze europejskie 2014 - 2020
Fundusze europejskie 2014 - 2020
 
Message center signs
Message center signsMessage center signs
Message center signs
 
Budaya,kerativitas dan inovasi
Budaya,kerativitas dan inovasiBudaya,kerativitas dan inovasi
Budaya,kerativitas dan inovasi
 
MacromolBioSci2004-4-601
MacromolBioSci2004-4-601MacromolBioSci2004-4-601
MacromolBioSci2004-4-601
 
Budaya,kreativitas dan inovasi
Budaya,kreativitas dan inovasiBudaya,kreativitas dan inovasi
Budaya,kreativitas dan inovasi
 
Digital marketing 101 social media
Digital marketing 101   social mediaDigital marketing 101   social media
Digital marketing 101 social media
 
Leveraging Social
Leveraging SocialLeveraging Social
Leveraging Social
 
Case Italia
Case ItaliaCase Italia
Case Italia
 
CV eldashash
CV eldashashCV eldashash
CV eldashash
 

Similar to 3.0

Spring tutorials
Spring tutorialsSpring tutorials
Spring tutorialsTIB Academy
 
Why Your Digital Transformation Strategy Demands Middleware Modernization
Why Your Digital Transformation Strategy Demands Middleware ModernizationWhy Your Digital Transformation Strategy Demands Middleware Modernization
Why Your Digital Transformation Strategy Demands Middleware ModernizationVMware Tanzu
 
SaaS transformation with OCE - uEngineCloud
SaaS transformation with OCE - uEngineCloudSaaS transformation with OCE - uEngineCloud
SaaS transformation with OCE - uEngineClouduEngine Solutions
 
SpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring FrameworkSpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring FrameworkSpringPeople
 
Microservices @ Work - A Practice Report of Developing Microservices
Microservices @ Work - A Practice Report of Developing MicroservicesMicroservices @ Work - A Practice Report of Developing Microservices
Microservices @ Work - A Practice Report of Developing MicroservicesQAware GmbH
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmpEmily Jiang
 
RightScale Webinar: Best Practices: Software Development Strategies Using Win...
RightScale Webinar: Best Practices: Software Development Strategies Using Win...RightScale Webinar: Best Practices: Software Development Strategies Using Win...
RightScale Webinar: Best Practices: Software Development Strategies Using Win...RightScale
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationNordic APIs
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxAbhijayKulshrestha1
 
MicroServices-Part-1.pdf
MicroServices-Part-1.pdfMicroServices-Part-1.pdf
MicroServices-Part-1.pdfchanhluc2112
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationJerod Johnson
 
Who's in your Cloud? Cloud State Monitoring
Who's in your Cloud? Cloud State MonitoringWho's in your Cloud? Cloud State Monitoring
Who's in your Cloud? Cloud State MonitoringKevin Hakanson
 
LeanIX Architecture Gathering 2018
LeanIX Architecture Gathering 2018LeanIX Architecture Gathering 2018
LeanIX Architecture Gathering 2018LeanIX GmbH
 
Venkatarao_2+Years_Experiance_JAVA2
Venkatarao_2+Years_Experiance_JAVA2Venkatarao_2+Years_Experiance_JAVA2
Venkatarao_2+Years_Experiance_JAVA2pediredla venkatarao
 
Azure Spring Cloud Workshop - June 17, 2020
Azure Spring Cloud Workshop - June 17, 2020Azure Spring Cloud Workshop - June 17, 2020
Azure Spring Cloud Workshop - June 17, 2020VMware Tanzu
 
AppliFire Blue Print Design Guidelines
AppliFire Blue Print Design GuidelinesAppliFire Blue Print Design Guidelines
AppliFire Blue Print Design GuidelinesAppliFire Platform
 
Application Development on Metapod
Application Development on MetapodApplication Development on Metapod
Application Development on MetapodCisco DevNet
 
Cloud-Native Patterns for Data-Intensive Applications
Cloud-Native Patterns for Data-Intensive ApplicationsCloud-Native Patterns for Data-Intensive Applications
Cloud-Native Patterns for Data-Intensive ApplicationsVMware Tanzu
 
Tools and Recipes to Replatform Monolithic Apps to Modern Cloud Environments
Tools and Recipes to Replatform Monolithic Apps to Modern Cloud EnvironmentsTools and Recipes to Replatform Monolithic Apps to Modern Cloud Environments
Tools and Recipes to Replatform Monolithic Apps to Modern Cloud EnvironmentsVMware Tanzu
 

Similar to 3.0 (20)

Spring tutorials
Spring tutorialsSpring tutorials
Spring tutorials
 
Why Your Digital Transformation Strategy Demands Middleware Modernization
Why Your Digital Transformation Strategy Demands Middleware ModernizationWhy Your Digital Transformation Strategy Demands Middleware Modernization
Why Your Digital Transformation Strategy Demands Middleware Modernization
 
SaaS transformation with OCE - uEngineCloud
SaaS transformation with OCE - uEngineCloudSaaS transformation with OCE - uEngineCloud
SaaS transformation with OCE - uEngineCloud
 
SpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring FrameworkSpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring Framework
 
Microservices @ Work - A Practice Report of Developing Microservices
Microservices @ Work - A Practice Report of Developing MicroservicesMicroservices @ Work - A Practice Report of Developing Microservices
Microservices @ Work - A Practice Report of Developing Microservices
 
Build12 factorappusingmp
Build12 factorappusingmpBuild12 factorappusingmp
Build12 factorappusingmp
 
RightScale Webinar: Best Practices: Software Development Strategies Using Win...
RightScale Webinar: Best Practices: Software Development Strategies Using Win...RightScale Webinar: Best Practices: Software Development Strategies Using Win...
RightScale Webinar: Best Practices: Software Development Strategies Using Win...
 
Scheduling in CCE
Scheduling in CCEScheduling in CCE
Scheduling in CCE
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API Integration
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptx
 
MicroServices-Part-1.pdf
MicroServices-Part-1.pdfMicroServices-Part-1.pdf
MicroServices-Part-1.pdf
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API Integration
 
Who's in your Cloud? Cloud State Monitoring
Who's in your Cloud? Cloud State MonitoringWho's in your Cloud? Cloud State Monitoring
Who's in your Cloud? Cloud State Monitoring
 
LeanIX Architecture Gathering 2018
LeanIX Architecture Gathering 2018LeanIX Architecture Gathering 2018
LeanIX Architecture Gathering 2018
 
Venkatarao_2+Years_Experiance_JAVA2
Venkatarao_2+Years_Experiance_JAVA2Venkatarao_2+Years_Experiance_JAVA2
Venkatarao_2+Years_Experiance_JAVA2
 
Azure Spring Cloud Workshop - June 17, 2020
Azure Spring Cloud Workshop - June 17, 2020Azure Spring Cloud Workshop - June 17, 2020
Azure Spring Cloud Workshop - June 17, 2020
 
AppliFire Blue Print Design Guidelines
AppliFire Blue Print Design GuidelinesAppliFire Blue Print Design Guidelines
AppliFire Blue Print Design Guidelines
 
Application Development on Metapod
Application Development on MetapodApplication Development on Metapod
Application Development on Metapod
 
Cloud-Native Patterns for Data-Intensive Applications
Cloud-Native Patterns for Data-Intensive ApplicationsCloud-Native Patterns for Data-Intensive Applications
Cloud-Native Patterns for Data-Intensive Applications
 
Tools and Recipes to Replatform Monolithic Apps to Modern Cloud Environments
Tools and Recipes to Replatform Monolithic Apps to Modern Cloud EnvironmentsTools and Recipes to Replatform Monolithic Apps to Modern Cloud Environments
Tools and Recipes to Replatform Monolithic Apps to Modern Cloud Environments
 

Recently uploaded

Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...SUHANI PANDEY
 
Karve Nagar ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Karve Nagar ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Karve Nagar ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Karve Nagar ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...tanu pandey
 
➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men 🔝manali🔝 Escorts S...
➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men  🔝manali🔝   Escorts S...➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men  🔝manali🔝   Escorts S...
➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men 🔝manali🔝 Escorts S...nirzagarg
 
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...SUHANI PANDEY
 
Top Rated Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...
Top Rated  Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...Top Rated  Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...
Top Rated Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...Call Girls in Nagpur High Profile
 
THE PROCESS OF SALTING AND CURING...pptx
THE PROCESS OF SALTING AND CURING...pptxTHE PROCESS OF SALTING AND CURING...pptx
THE PROCESS OF SALTING AND CURING...pptxElaizaJoyVinluan
 
The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...ranjana rawat
 
VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...
VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...
VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...SUHANI PANDEY
 
Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...
Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...
Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...MOHANI PANDEY
 
VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...
VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...
VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...SUHANI PANDEY
 
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...SUHANI PANDEY
 
WhatsApp Chat: 📞 8617697112 Call Girl Reasi is experienced
WhatsApp Chat: 📞 8617697112 Call Girl Reasi is experiencedWhatsApp Chat: 📞 8617697112 Call Girl Reasi is experienced
WhatsApp Chat: 📞 8617697112 Call Girl Reasi is experiencedNitya salvi
 
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...SUHANI PANDEY
 
Hinjewadi ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready Fo...
Hinjewadi ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready Fo...Hinjewadi ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready Fo...
Hinjewadi ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready Fo...tanu pandey
 
Call Girls Sb Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Sb Road Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Sb Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Sb Road Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Booking open Available Pune Call Girls Sanaswadi 6297143586 Call Hot Indian ...
Booking open Available Pune Call Girls Sanaswadi  6297143586 Call Hot Indian ...Booking open Available Pune Call Girls Sanaswadi  6297143586 Call Hot Indian ...
Booking open Available Pune Call Girls Sanaswadi 6297143586 Call Hot Indian ...Call Girls in Nagpur High Profile
 
VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...
VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...
VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...SUHANI PANDEY
 
VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...SUHANI PANDEY
 

Recently uploaded (20)

Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
 
Karve Nagar ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Karve Nagar ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Karve Nagar ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Karve Nagar ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men 🔝manali🔝 Escorts S...
➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men  🔝manali🔝   Escorts S...➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men  🔝manali🔝   Escorts S...
➥🔝 7737669865 🔝▻ manali Call-girls in Women Seeking Men 🔝manali🔝 Escorts S...
 
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
 
Top Rated Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...
Top Rated  Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...Top Rated  Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...
Top Rated Pune Call Girls Yashwant Nagar ⟟ 6297143586 ⟟ Call Me For Genuine ...
 
THE PROCESS OF SALTING AND CURING...pptx
THE PROCESS OF SALTING AND CURING...pptxTHE PROCESS OF SALTING AND CURING...pptx
THE PROCESS OF SALTING AND CURING...pptx
 
The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Tingre Nagar 8250192130 Will You Miss Thi...
 
VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...
VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...
VVIP Pune Call Girls Chakan WhatSapp Number 8005736733 With Elite Staff And R...
 
Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...
Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...
Get Premium Austin Town Call Girls (8005736733) 24x7 Rate 15999 with A/c Room...
 
VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...
VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...
VIP Model Call Girls Balaji Nagar ( Pune ) Call ON 8005736733 Starting From 5...
 
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
 
WhatsApp Chat: 📞 8617697112 Call Girl Reasi is experienced
WhatsApp Chat: 📞 8617697112 Call Girl Reasi is experiencedWhatsApp Chat: 📞 8617697112 Call Girl Reasi is experienced
WhatsApp Chat: 📞 8617697112 Call Girl Reasi is experienced
 
(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7
(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7
(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7
 
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
 
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
 
Hinjewadi ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready Fo...
Hinjewadi ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready Fo...Hinjewadi ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready Fo...
Hinjewadi ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready Fo...
 
Call Girls Sb Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Sb Road Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Sb Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Sb Road Call Me 7737669865 Budget Friendly No Advance Booking
 
Booking open Available Pune Call Girls Sanaswadi 6297143586 Call Hot Indian ...
Booking open Available Pune Call Girls Sanaswadi  6297143586 Call Hot Indian ...Booking open Available Pune Call Girls Sanaswadi  6297143586 Call Hot Indian ...
Booking open Available Pune Call Girls Sanaswadi 6297143586 Call Hot Indian ...
 
VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...
VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...
VIP Model Call Girls Ranjangaon ( Pune ) Call ON 8005736733 Starting From 5K ...
 
VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Alandi Road WhatSapp Number 8005736733 With Elite Staff ...
 

3.0

  • 1. 1 Ramkrishna IT Systems Vivek S. Kulkarni Ramkrishna IT Systems
  • 2. 2 Ramkrishna IT Systems • Understand the architecture of Spring Framework • Understand Dependency Injection • AOP • Develop sample applications using – Spring AOP – Spring JDBC Support – Spring Hibernate integration – Transactional Support in Spring – Spring Remoting – Spring MVC
  • 3. 3 Ramkrishna IT Systems • Installing and Using STS • Writing a simple Spring app • Understanding ApplicationContext • Learn bean lifecycle • Learning Dependency Injection – Constructor injection – Setter Injection • Annotation based DI
  • 4. 4 Ramkrishna IT Systems Course Agenda: Day 2 • • • • • AOP : Advice, JoinPoints, PointCuts and Aspects Adding behavior to an application using aspects Introducing data access with Spring Simplifying JDBC-based data access Driving database transactions in a Spring environment
  • 5. 5 Ramkrishna IT Systems Course Agenda: Day 3 • Introducing object-to-relational mapping (ORM) • Getting started with Hibernate in a Spring environment • Web application architecture • Getting started with Spring MVC • Spring Remoting
  • 6. 6 Ramkrishna IT Systems Overview of the Spring Framework Introducing Spring in the context of enterprise application architecture
  • 7. 7 Ramkrishna IT Systems What is Spring ? A light-weight dependency injection and aspect- oriented container and framework
  • 8. 8 Ramkrishna IT Systems What is Spring ? Light-Weight : Processing overhead required by spring is negligible Non-intrusive : Spring enabled application may not have any dependency on spring, They can be run inside or outside of the spring framework without any change in source code. Dependency Injection : Promotes program-to-interface design principle, thus promotes loose coupling. This technique is reverse of JNDI –i.e. you do not look-up for dependant objects in your code, container figures out required objects and creates them and INJECTS them.
  • 9. 9 Ramkrishna IT Systems What is Spring ? Aspect-oriented : Application programmers do not write logic for cross-cutting concerns such as logging, transaction, security. The Spring framework provides the support for AOP. Container : Spring is a container in the sense that it contains and manages the lifecycle and configuration of application objects. The association of different application objects, their dependencies, their initialization etc. is configured and container does the rest. Framework : A large number of pre-defined classes and interfaces provide a host of functionality required like transaction management, MVC, integration with persistence frameworks and so on. You write only business logic.
  • 10. 10 Ramkrishna IT Systems Goal of the Spring Framework • Provide comprehensive infrastructural support for developing enterprise Java™ applications – Spring deals with the plumbing – So you can focus on solving the domain problem
  • 11. 11 Ramkrishna IT Systems Spring’s Support (1) • Core support Application Configuration Enterprise Integration Data Access
  • 12. 12 Ramkrishna IT Systems Application Configuration • A typical application system consists of several parts working together to carry out a use case Component A Component B Component C
  • 13. 13 Ramkrishna IT Systems A Typical Use Case Spring Introduction transfer( “300.00”, “1”, “2”) updateAccount(a2); new new loadAccount(“1”); a1 loadAccount(“2”); a2 debit(“300.00”) credit(“300.00”) updateAccount(a1); Use Case : Bank Money Transfer
  • 14. 14 Ramkrishna IT Systems Spring’s Configuration Support • Spring provides support for assembling such an application system from its parts – Parts do not worry about finding each other – Any part can easily be swapped out
  • 15. 15 Ramkrishna IT Systems TransferServiceImpl Money Transfer System Assembly Spring Part 2 Assembly JdbcAccountRepository Part 1 (1) new JdbcAccountRepository(…); (2) new TransferServiceImpl(); (3) service.setAccountRepository(repository); 8
  • 16. 16 Ramkrishna IT Systems } Parts are Just Plain Java Objects public void setAccountRepository(AccountRepository ar) { accountRepository = ar; } … } Part 1 Depends on service interface; conceals complexity of implementation; allows for swapping out implementation Part 2 public class JdbcAccountRepository implements AccountRepository { … Implements a service interface public class TransferServiceImpl implements TransferService { private AccountRepository accountRepository;
  • 17. 17 Ramkrishna IT Systems Enterprise Integration • Enterprise applications do not work in isolation • They require enterprise services and resources Database Connection Pool Database Transactions Security Messaging Remote Access Caching
  • 18. 18 Ramkrishna IT Systems Spring Enterprise Integration • Spring helps you integrate powerful enterprise services into your application – While keeping your application code simple and testable • Plugs into all Java EE™ application servers – While capable of standalone usage
  • 19. 19 Ramkrishna IT Systems TransferServiceImpl Enterprise Money Transfer with Spring Spring JdbcAccountRepository DataSource For DB Connection Pooling 13 TransactionManager For DB Transactions MBean Exporter For JMX Management Ramkrishna IT Systems
  • 20. 20 Ramkrishna IT Systems Simple Application Code public class TransferServiceImpl implements TransferService { @Transactional public TransferConfirmation transfer(MonetaryAmount amount, in srcAccountId, int targetAccountId ){ Account src = accountRepository.loadAccount(srcAccountId); Account target = accountRepository.loadAccount(targetAccountId); src.debit(amount); target.credit(amount); accountRepository.updateAccount(src); accountRepository.updateAccount(target); return new TransferConfirmation(...); } } Tells Spring to run this method in a database transaction Ramkrishna IT Systems
  • 21. 21 Ramkrishna IT Systems Spring makes data access easier to – Manage resources for you – Provide API helpers – Support all major data access technologies It also Supports Integration of Hibernate iBatis JPA Data Access
  • 22. 22 Ramkrishna IT Systems • • Acquisition of the connection Participation in the transaction • • • • Execution of the statement Processing of the result set Handling of any exception Release of the connection All handled by Spring Spring JDBC in a Nutshell Spring's JDBC helper class int count = jdbcTemplate.queryForInt( "SELECT COUNT(*) FROM CUSTOMER");
  • 23. 23 Ramkrishna IT Systems Spring Framework History • http://www.springsource.org/download • Spring 3.0 (released 12/09) – Requires Java 1.5+ and JUnit 4.7+ – REST support, JavaConfig, SpEL, more annotations • Spring 2.5 (released 11/07) – Requires Java 1.4+ and supports JUnit 4 – Annotation DI, @MVC controllers, XML namespaces • Spring 2.0 (released 10/06) – Compatible with Java 1.3+ – XML simplification, async JMS, JPA, AspectJ support
  • 24. 24 Ramkrishna IT Systems Download and install STS 2.3.3.M2 from SpringSource.com: • Eclipse Based • Has Spring Plug-ins • Auto-Completion for Spring Config files • Comes with Tomcat plugged-in •Comes with Junit-plugged-in
  • 25. 25 Ramkrishna IT Systems Lab -1 : 30 minutes Use STS for creating non-Spring App
  • 26. 26 Ramkrishna IT Systems Dependency Injection : Alternatives • Creation using singletons • Factory Pattern • Reflection with Strategy Pattern • Decorator • Service Locator
  • 27. 27 Ramkrishna IT Systems Dependency Injection : Responsibility of co-ordination and collaboration is taken away from objects • Decoupling : Program-to-Interface principle • Dependency graph • Clean code • Enforcing immutability if required • Enforcing initialization • Runtime changes in dependency rules • Objects focus on their task and not worried about availability of their dependent objects
  • 28. 28 Ramkrishna IT Systems Steps : 1.Identify the dependencies 2.Decide optional dependancies 3.Wire them together in XML file 4.Instantiate ApplicationContext(container) 5.Get Instance by calling getBean() method Dependency Injection : Using Spring
  • 29. 29 Ramkrishna IT Systems With Spring ApplicationContext ctx = … Bank bank = ctx.getBean(“bankService”); bank.withdraw(1234, 500); Bank Service Example Without Spring : AccountRepository repos = new AccountRepositoryImpl(); Bank bank = new BankImpl(repos); bank.withdraw(1234, 500); No need to instantiate AccountRepository, No knowledge of Bank Implementation class
  • 30. 30 Ramkrishna IT Systems With Spring ApplicationContext ctx = … Bank bank = ctx.getBean(“bankService”); bank.withdraw(1234, 500); Bank Service Example Spring Bean Configuration File : <bean id="bankService" class="bank.server.internal.BankImpl"> <constructor-arg ref="accountRepo"/> </bean> <bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl"> </bean> “bankService” must match with bean id
  • 31. 31 Ramkrishna IT Systems Equivalent to AccountRepository accountRepo = new bank.server.internal.AccountRepositoryImpl(); Bank Bank = new BankImpl(accountRepo); Bank Service Example Spring Bean Configuration File : <bean id="bankService" class="bank.server.internal.BankImpl"> <constructor-arg ref="accountRepo"/> </bean> <bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl"> </bean> Application Context bankService Instance of BankImpl accountRepo Instance of AccountRepositoryImpl
  • 32. 32 Ramkrishna IT Systems Lab -2 : 40 minutes Use STS for creating Spring App
  • 33. 33 Ramkrishna IT Systems Equivalent to AccountRepository accountRepo = new bank.server.internal.AccountRepositoryImpl(); DBAccessRService dbAccessService = new bank.server.internal.DBAccessServiceImpl(); Bank Bank = new BankImpl(accountRepo, dbAccessService); Constructor Dependency Injection Spring Bean Configuration File : <bean id="bankService" class="bank.server.internal.BankImpl"> <constructor-arg ref="accountRepo"/> <constructor-arg ref=“dbAccessService"/> </bean> <bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl"> </bean> </bean> <bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl"> </bean> 2 class instances are expected to be passed to constructor
  • 34. 34 Ramkrishna IT Systems Equivalent to AccountRepository accountRepo = new bank.server.internal.AccountRepositoryImpl(); DBAccessRService dbAccessService = new bank.server.internal.DBAccessServiceImpl(); Bank Bank = new BankImpl(); bank.setAccountRepository(accountRepo ); bank. setDBAccess(dbAccessService); Setter Dependency Injection Spring Bean Configuration File : <bean id="banService" class="bank.server.internal.BankImpl"> <property name=“accountRepository” ref="accountRepo"/> <property name=“dBAccess” ref=“dbAccessService"/> </bean> <bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl"> </bean> </bean> <bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl"> </bean> 2 class instances are expected to be passed to Setters
  • 35. 35 Ramkrishna IT Systems Setter vis-à-vis constructor Dependency Injection Constructor Dependency : When Do I Use Enforce mandatory dependancy Promote Immutability(by assigning dependencies to final vars) Setter Dependency : When do I Use Allow optional dependencies Allow defaults Config file is more readable(property names are generally meaningful) Inherited automatically(Constructors are required to be written in sub-classes)
  • 36. 36 Ramkrishna IT Systems Mix-and –Match <bean id="banService" class="bank.server.internal.BankImpl"> <constructor-arg ref="accountRepo"/> <property name=“dbAccess”ref=“dbAccessService"/> </bean> <bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl"> </bean> </bean> <bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl"> </bean> Setter vis-à-vis constructor Dependency Injection
  • 37. 37 Ramkrishna IT Systems Mix-and –Match <bean id="banService" class="bank.server.internal.BankImpl"> <constructor-arg ref="accountRepo"/> <property name=“dbAccess”ref=“dbAccessService"/> </bean> <bean id="accountRepo" class="bank.server.internal.AccountRepositoryImpl"> </bean> </bean> <bean id=" dbAccessService " class=“bank.server.internal.DBAccessServiceImpl"> </bean> Reccomendations Use Constructor DI for required properties Use Setter Injection for optional properties and defaults. Be consistent in the approach.
  • 38. 38 Ramkrishna IT Systems <bean id=“someService" class=“example.SomeServiceImpl"> <property name=“balance” value=“10000"/> </bean> Container takes care of auto conversion of scalar values . Throws Exception if type mis-match(non-convertible types) Injection for scalars Injecting Collections class BankImpl implements Bank{ Collection<Account> accounts; public void showAccount(){ for(Account acct : accounts){ System.out.println(acct.toString()); } }
  • 39. 39 Ramkrishna IT Systems <bean id=“bankService" class=“bank.server.BankImpl"> <property name=“accounts”> <list> <ref bean =“current” > <ref bean =“savings” /> <ref bean = “FD” /> <ref bean =“housingLoan /> </list> </bean> Injecting Collections class BankImpl implements Bank{ Collection<AccountService> accountServices; BankImpl(Collection<AccountService> accounts){ this. accountServices = accounts; } public void showAccountServices(){ for(AccountService acct : accountServices){ System.out.println(acct.toString()); } } <set> <ref bean =“current” > <ref bean =“savings” /> <ref bean = “FD / <ref bean =“housingLoan”/> <ref bean =“housingLoan”/> //duplicate entry </set>
  • 40. 40 Ramkrishna IT Systems <bean id=“bankService" class=“bank.server.BankImpl"> <property name=“accounts”> <map> <entry key=“CurrentAccount” value-ref=“current” > <entry key=“SaningsAccount” value-ref =“savings” /> <entry key=“FixedDeposit” value-ref = “FD” /> </map> </bean> Injecting Collections class BankImpl implements Bank{ Map<AccountService> accountServices; BankImpl(Collection<AccountService> accounts){ this. accountServices = accounts; } public void showAccountServices(){ for(String accountType : accountServices.keySet()){ System.out.println(accountServices.get(acctType).toString()); } } <map> <entry key-ref=“someBean” value-ref “otherbean” /> </map > OR <map> <entry key=“someScalarType” value=“someScalarType” /> </map>
  • 41. 41 Ramkrishna IT Systems <bean id=“bankService" class=“bank.server.BankImpl"> <constructor-arg name=“accounts”> <props> <prop key=“CurrentAccount”>current </prop> <prop key=“SaningsAccount” >savings</prop> <prop key=“FixedDeposit” >FD</prop> </props> </bean> Injecting Collections : Properties class BankImpl implements Bank{ Map<AccountService> accountServices; BankImpl(Properties accounts){ this. accountServices = accounts; } public void showAccountServices(){ for(String accountType : accountServices.keySet()){ System.out.println(accountServices.get(acctType).toString()); } } <props> <prop key=“keyString” >value</prop> </props>
  • 42. 42 Ramkrishna IT Systems DI Advance Options:Inner-beans <bean id="bankService" class="bank.server.internal.BankImpl" abstract="true" > <constructor-arg > <bean class="bank.server.internal.AccountRepositoryImpl" /> </constructor-arg> </bean> Implications : 1. Inner beans are always lazy initialized as opposed to early-init of outer beans 2. Inner beans are always scoped to scope of the outer bean
  • 43. 43 Ramkrishna IT Systems Options To do following 1. Control number of instances of a specific bean : 1 Per application (scope=“singleton” this is default) 1 Per usage (scope”prototype”)(This is useful if domain classes are used as beans) 1 Per user-request (If HTTP capable Spring context is used using SpringMVC then scope=“request”) 1 per session (If HTTP capable Spring context is used using SpringMVC then scope=“session”) Singleton here is different from singleton pattern. Here singleton does not mean multiple instances cannot be created, all it means is application context keeps only one copy. c tx.getBean(“beanName”) method uses the scope attribute to decide the creation <bean id=“someId” class=“someClass” scope=“prototype” /> Controlling Bean Creation
  • 44. 44 Ramkrishna IT Systems Bean Scopes : singleton(default)
  • 45. 45 Ramkrishna IT Systems Bean Scopes : prototype Destruction of prototypes is NOT managed by container . You have to do the clean-up(call destroy method etc) explicitly in your client code OR create custom-BeanPostProcessor to do it for you.
  • 46. 46 Ramkrishna IT Systems Bean Scopes : prototype Destruction of prototypes is NOT managed by container . You have to do the clean-up(call destroy method etc) explicitly in your client code(You need to type-cast ctx to ConfigurableApplicationContext and call close() OR create custom-BeanPostProcessor to do it for you. Prototypes are not eager-initialized unlike singletons Prototypes are injected once per singleton dependants. Mutliple calls to getBean(“bankService”) will not refresh(re-instantiate) the prototype.
  • 47. 47 Ramkrishna IT Systems Get same bean class with different id’s and with some common DI. Over ride few property values. Minimize repetitive declarations in xml parent attribute for sub-beans No class attribute abstract=“true” for parent bean DI Advance Options:sub-beans <bean id="bankService" class="bank.server.internal.BankImpl" abstract="true" scope="singleton" > <constructor-arg > <bean class="bank.server.internal.AccountRepositoryImpl" scope="singleton"/> </constructor-arg> <constructor-arg> <set> <ref bean="current" /> <ref bean="saving" /> <ref bean="loan"/> </set> </constructor-arg> <property name="bankName" value="RBI" /> <property name="branchCode" value="1234" /> </bean> <bean id="sbi" parent="bankService" > <property name="bankName" value="StateBank" /> </bean> <bean id="axis" parent="bankService" > <property name="branchCode" value="345" /> </bean>
  • 48. 48 Ramkrishna IT Systems Parent bean could be an abstract class an interface, a concrete class or may not be a class at all( it is just a set of properties that child beans share). abstract=“true” for parent bean Child beans are actually classes which are un-related classes sharing common properties. Child beans can overwrite the property values. DI Advance Options:sub-beans with only property inheritance <bean id="bankService" abstract="true" > <constructor-arg > <bean class="bank.server.internal.AccountRepositoryImpl" /> </constructor-arg> <constructor-arg> <props> <prop key="CURRENT ACCOUNT" >hello </prop> <prop key="SAVING ACCOUNT">saving</prop> <prop key="LOAN ACCOUNT" >loan </prop> </props> </constructor-arg> <property name="branchCode" value="1234" /> <property name="bankName" value="SBI"></property> </bean> <bean id="sbi" class="bank.server.internal.SBI" parent="bankService" > </bean> <bean id="axis" class="bank.server.internal.AXIS" parent="bankService" > <property name="branchCode" value="345" /> <property name="bankName" value="AXIS"></property> </bean> </bean>
  • 49. 49 Ramkrishna IT Systems Allows runtime injection of methods into java classes(like template method pattern) 2 Forms Getter Injection : Returns a different spring bean at runtime Method replacements : Runtime injection of different implementation Injecting Methods 1.Getter Injection : •Bean class could be abstract(or concrete) •abstract class Magician { • abstract MagicBox getBox(); •} •The method which needs to be replaced(injected) at runtime comes from some other concrete class. •To replace method, bytecode is instrumented by CGLIB at runtime and a subclass of the current class is created and the method is injected into it •So class who’s method is to be replaced can not be final, method cannot be final either.
  • 50. 50 Ramkrishna IT Systems Allows runtime injection of methods into java classes(like template method pattern) 2 Forms Method injection using lookup-method: This is a getter Injection which returns a different bean at runtime. Method Injection using Method Replacer: Injecting Methods Choo Mantar !!
  • 51. 51 Ramkrishna IT Systems Allows runtime injection of methods into java classes(like template method pattern) 2 Forms Method replacements : Injection Using Method-replacer: Injecting Methods 2. Method Injection using Method-Replacer : public class ElephantReplacer implements MethodReplacer { public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable { //System.out.println("Object whos method is to be replaced"+arg0.toString()+" Name of Method "+arg1.getName()+" MYSORE ELEPHANT "+arg2[0]); return "MYSORE ELEPHANT "; } }
  • 52. 52 Ramkrishna IT Systems Using non-managed beans (User instantiated beans) with Spring DI These are normally Domain Beans(Pojos) created by say hibernate session.load(). You want these objects to be monitored for dependency etc. by Spring. Use VM args to enable Load Time Weaving of AspectJ’s Aspect -javaagent:C:core-spring-3.1.0.RELEASErepositoryorgaspectjaspectjweaver1.6.8aspectjweaver-1.6.8.jar Injecting Non-spring beans import org.springframework.beans.factory.annotation.Configurable; @Configurable("magician") public class Magician { String magicwords; MagicBox box; …..} <context:spring-configured /> <bean id="magician" class="com.rits.Magician" > <property name="box" ref="magicbox"></property> <property name="magicwords" value="Choo Mantar !!" /> </bean> <bean id="magicbox" class="com.rits.MagicBoxImpl" />
  • 53. 53 Ramkrishna IT Systems Lab -3 : 45 minutes Using Setter Injection, Collection Injections
  • 54. 54 Ramkrishna IT Systems <bean id=“bankService" class=“bank.server.BankImpl"> <property name=“accountService” ref=“acctRepo” /> </bean> <bean id=“acctRepo” class=“bank.server.internal.AccountRepositoryImpl” /> OR <bean id=“bankService" class=“bank.server.BankImpl“ autowire=“byName” /> <bean id=“acctRepo” class=“bank.server. internal.AccountRepositoryImpl” /> AutoWiring Autowiring of 4 types 1. byName : Attempts to find a bean in the container whose name(or ID) is the same as the name of the property being wired(injected) 2. byType : Attempts to find a single bean in the container whose type matches the type of the property being wired. If not found it ignores, if multiple macthes found then throws org.springframework.beans.factory.UnsatisfiedDependencyException 3.constructor : Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired. In case of ambiguity it throws org.springframework.beans.factory.UnsatisfiedDependencyException 4. autodetect : Tries to apply constructor stretagy first if matching constructor found then it will use contructor injection if not then will apply byType strategy and is matching type found then applies setterInjection if neither is found then leaves property un-initialized.
  • 55. 55 Ramkrishna IT Systems Special attributes : factory-method/init- method/destroy-method 1 <bean id=“someId” class=“someClass” factory-method=“getInstance() /> A static object creation method can be invoked instead of calling constructor. Works for objects with private constructors and true singletons. <bean id=“someBean” class=“someClass” init-method=“doInit” /> <bean id=“someBean” class=“someClass” destroy-method=“doDestroy” /> Controlling Bean Creation
  • 56. 56 Ramkrishna IT Systems Special attributes : factory-bean Option-1 : POJO factory Useful for existing factory classes <bean id=“someId” class=“someClass” factory-bean=“someFactory” factory- method=“getInstance” /> <bean id=“someFactory” class=“someFactoryClass” /> An instance object creation method can be invoked instead of calling constructor. Works for objects with private constructors and true singletons Bean Creation Using factory-bean
  • 57. 57 Ramkrishna IT Systems Option-II Use FactoryBean implementation <bean id=“someFactoryId” class=“someFactoryClass” /> <bean id=“bankService” class=“BankImpl” > <property name=“service” ref=“someFactoryId” /> </bean> A Dependency Injection of the Object returned by the Template Factory is done transparently (calling getObject Method) e.g. Class SomeFactoryClass implements FactoryBean<SomeService>{ public SomeService getObject() throws Exception { return new SomeSevice() ;} Bean Creation : Using FactoryBean interface
  • 58. 58 Ramkrishna IT Systems FactoryBean • Spring uses FactoryBean Template interface RemoteProxies are created using FactoryBean – DataSources are created using FactoryBean for accessing Hibernate, iBatis etc.
  • 59. 59 Ramkrishna IT Systems ApplicationContext • Spring provides a lightweight container called “ApplicationContext” – 3 flavours for resource(config file) loading – 1. new ClassPathXmlApplicationContext(“com/sungard/application-config.xml”); – $CLASSPATH/com/sungard/application-config.xml” – 2. new FileSystemXmlApplicationContext(c:somedirapplication-config.xml”); – OR – new FileSystemXmlApplicationContext(../application-config.xml”); – 3. XmlWebApplicationContext : Created by WebCOntainers resource loading happens relative to WEB-INF/
  • 60. 60 Ramkrishna IT Systems ApplicationContext • Loading multiple config files • ApplicationContext ctx = • new ClassPathXmlApplicationConext(new String[]{“application-config.xml”, “oracle-infra-config.xml” , file:../someOther-config.xml”}); • Separate files for Infrastructure config than actual application beans.
  • 61. 61 Ramkrishna IT Systems Phases of the Application Lifecycle Initialization • Prepares for use • Application services – Are created – Configured – May allocate system resources • Application is not usable until this phase is complete Use • Used by clients • Application services – Process client requests – Carry out application behaviors • 99.99% of the time is spent in this phase Destruction • Shuts down • Application services – Release any system resources – Are eligible for garbage collection 11
  • 62. 62 Ramkrishna IT Systems Application Initialization When We create an instance of the ApplicationContext : Initialization is Complete During applicationContext Creation, What Happens? (when we call new CLassPathXMLApplicationContext(…) 1. Loading of Bean Definitions from config files 2. Creates dependancy graph 3. All singleton beans and pre-instantiated (unless lazy-init=“true” ) 4. Initialization of bean Instances
  • 63. 63 Ramkrishna IT Systems Application Initialization : Loading Bean Definitions •The XML files are parsed. Bean Definitions are loaded into the context’s BeanFactory Special Beans “BeanFactoryPostProcessor” are invoked These special beans can modify the bean definitions before creating the objects.
  • 64. 64 Ramkrishna IT Systems Load Bean Definitions application-config.xml <beans> Application Context BeanFactory transferService accountRepository dataSource postProcess(BeanFactory) BeanFactoryPostProcessors <bean id=“transferService” … <bean id=“accountRepository”… </beans> test-infrastructure-config.xml <beans> <bean id=“dataSource” … </beans> Can modify the definition of any bean in the factory before any objects are created 17
  • 65. 65 Ramkrishna IT Systems BeanFactoryPostProcessor •An Extension Point to modify bean definitions programatically before loading bean definitions •Several useful special BeanFactoryPostProcessor beans are provided by Spring • e.g. PropertyPlaceholderConfigurer It substitutes ${variables} in bean definitions with values from .properties files CustomEditorConfigurer It loads custom editors into beanfactory. You can write your own by implementing BeanFactoryPostProcessor interface
  • 66. 66 Ramkrishna IT Systems Custom Property Editors class Contact{ public PhoneNumber getPhone() { return phone; } public void setPhone(PhoneNumber phone) { this.phone = phone; } public class PhoneNumber { String areaCode; String stdCode; String number; public PhoneNumber(String areaCode, String stdCode, String number) { super(); this.areaCode = areaCode; this.stdCode = stdCode; this.number = number; } <bean id="contact" class="com.rits.training.Contact" > <property name="phone" value="512-230-9630" /> </bean> Need to convert String into PhoneNumber
  • 67. 67 Ramkrishna IT Systems mport java.beans.PropertyEditorSupport; public class PhoneEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { String stripped = stripOutNonNumerics(text); String areaCode = stripped.substring(0,3); String prefix = stripped.substring(3,6); String number = stripped.substring(6); PhoneNumber phone = new PhoneNumber(areaCode,prefix, number); this.setValue(phone); } private String stripOutNonNumerics(String original){ StringBuffer allNumeric = new StringBuffer(); for(int i=0; i < original.length(); i++){ char c = original.charAt(i); if(Character.isDigit(c)){ allNumeric.append(c); }
  • 68. 68 Ramkrishna IT Systems We should tell Spring about our custom PhoneEditor <bean id="contact" class="com.rits.training.Contact" > <property name="phone" value="512-230-9630" /> </bean> <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="com.rits.training.PhoneNumber"> <bean id="phoneEditor" class="com.rits.training.PhoneEditor" /> </entry> </map> </property> </bean> CustomEditorConfigurer is a BeanFactoryPostProcessor. It registers PhoneEditor with BeanFactory, so BeanFactory would invoke this before creating Contact bean.
  • 69. 69 Ramkrishna IT Systems BeanFactoryPostProcessor : PropertyPlaceholderConfigurer <property name=“URL” value=“${datasource.url}” /> <property name=“user” value=“${datasource.user}” /> <bean class=“org.springframework.beans.factory.config. PropertyPlaceholderConfigurer”> <property name=“location” value=“/WEB-INF/datasource.properties” /> File where the variable values reside datasource.url=jdbc:oracle:thin:@localhost:1521:BANK datasource.user=moneytransfer-app </bean> </beans> datasource.properties Variables to replace Easily editable 21 <beans> <bean id=“dataSource” class=“com.oracle.Jdbc.pool.OracleDataSource”>
  • 70. 70 Ramkrishna IT Systems Simplifying configuration with <context:property-placeholder> <beans ... > <bean id=“dataSource” class=“com.oracle.Jdbc.pool.OracleDataSource”> <property name=“URL” value=“${datasource.url}” /> <property name=“user” value=“${datasource.user}” /> </bean> <context:property-placeholder location=“datasource.properties” /> </beans> Creates the same PropertyPlaceholderConfigurer bean definition in a more concise fashion
  • 71. 71 Ramkrishna IT Systems Registering for an Initialization Callback with InitializingBean • Initialization technique used prior to Spring 2.5 – Disadvantage: Ties your code to the framework – Advantage: The only way to enforce initialization code should run (not affected by configuration changes) package org.springframework.beans.factory; public interface InitializingBean { public void afterPropertiesSet(); } PropertyPlaceholderConfigurer 20 How PropertyPlaceholderConfigurer Works Spring Application Context (after bean definitions are loaded) postProcess(BeanFactory) Bean definition “dataSource” URL=${datasource.url} user=${datasource.user} Bean definition “dataSource” URL=Jdbc:oracle:… user=moneytransfer-app
  • 72. 72 Ramkrishna IT Systems Steps involved in Initializing Bean Instances • Each bean is eagerly instantiated by default – Created in the right order with its dependencies injected • After dependency injection each bean goes through a post-processing phase – Where further configuration and initialization can occur • After post processing the bean is fully initialized and ready for use – Tracked by its id until the context is destroyed
  • 73. 73 Ramkrishna IT Systems Bean Initialization Steps Bean Instantiated Dependencies InJected Bean Post Processed Bean Ready For Use
  • 74. 74 Ramkrishna IT Systems Bean Post Processing • Bean post processing can be broken down into two steps – Initialize the bean if instructed – Call special BeanPostProcessors to perform additional configuration
  • 75. 75 Ramkrishna IT Systems Initialize the Bean if Instructed • A bean can optionally register for one or more initialization callbacks – Useful for executing custom initialization behaviors • There's more than one way to do it – JSR-250 @PostConstruct – <bean/> init-method attribute – Implement Spring's InitializingBean interface
  • 76. 76 Ramkrishna IT Systems Registering for Initialization with @PostConstruct public class TransferServiceImpl { @PostConstruct void init() { // your custom initialization code Tells Spring to call init after DI No restrictions on method name or visibility } } • This is the preferred initialization technique – Flexible, avoids depending on Spring APIs – Requires Spring 2.5 or better 30
  • 77. 77 Ramkrishna IT Systems Enabling Common Annotation- Based Initialization • @PostConstruct will be ignored unless Spring is instructed to detect and process it <beans> <bean id=“transferService” class=“example.TransferServiceImpl” /> <bean class=“org.springframework.context.annotation. CommonAnnotationBeanPostProcessor” /> </beans> Detects and invokes any methods annotated with @PostConstruct
  • 78. 78 Ramkrishna IT Systems Registering for an Initialization Callback with InitializingBean • Initialization technique used prior to Spring 2.5 – Disadvantage: Ties your code to the framework – Advantage: The only way to enforce initialization code should run (not affected by configuration changes) package org.springframework.beans.factory; public interface InitializingBean { public void afterPropertiesSet(); }
  • 79. 79 Ramkrishna IT Systems Simplifying Configuration with <context:annotation-config> <beans> <bean id=“transferService” class=“example.TransferServiceImpl” /> <context:annotation-config/> </beans> Enables multiple BeanPostProcessors, including: • RequiredAnnotationBeanPostProcessor • CommonAnnotationBeanPostProcessor
  • 80. 80 Ramkrishna IT Systems Initializing a Bean You Do Not Control • Use init-method to initialize a bean you do not control the implementation of <bean id=“current” class="bank.server.internal.CurentAccount" init-method=“initialize”> … </bean> Method can be any visibility, but must have no arguments 34 Class with no Spring dependency
  • 81. 81 Ramkrishna IT Systems Initialization : @Required •RequiredAnnotationBeanPostProcessor e.g. @Required public void setInterestRate(float interestRate) { this.interestRate = interestRate; System.out.println("Saving Account : interest "); }rate property set”); If interestRate property of this class is not configured in config file for DI, container would throw org.springframework.beans.factory.BeanCreationException This is a useful technique for enforcing the initialization
  • 82. 82 Ramkrishna IT Systems Destroying : @PreDestroy •BeanPostProcessor Called when ctx.close() is invoked. @PreDestroy public void releaseResources() { System.out.println(“Resources released”); } This is a useful technique for enforcing the release of some resources like DB connections etc.
  • 83. 83 Ramkrishna IT Systems Destroying : destroy-method •BeanPostProcessor Called when ctx.close() is invoked. <bean id=“somBean” class=“SomeClass” destroy-method=“someMethod” /> This is a useful technique for enforcing the release of some resources like DB connections etc. 43 Topics in this session • Introduction to Spring's XML namespaces • The lifecycle of a Spring application context – The initialization phase – The use phase – The destruction phase • Bean scoping Use DestructionInitialization
  • 84. 84 Ramkrishna IT Systems Destroying : destroy-method •BeanPostProcessor Called when ctx.close() is invoked. <bean id=“somBean” class=“SomeClass” destroy-method=“someMethod” /> This is a useful technique for enforcing the release of some resources like DB connections etc. 43 Topics in this session • Introduction to Spring's XML namespaces • The lifecycle of a Spring application context – The initialization phase – The use phase – The destruction phase • Bean scoping Use DestructionInitialization 44 The Lifecycle of a Spring Application Context (2) - The Use Phase • When you invoke a bean obtained from the context the application is used • But exactly what happens in this phase? ApplicationContext context = // get it from somewhere // Lookup the entry point into the application TransferService service = (TransferService) context.getBean(“transferService”); // Use it! service.transfer(new MonetaryAmount(“50.00”), “1”, “2”);
  • 85. 85 Ramkrishna IT Systems 45 Inside The Bean Request (Use) Lifecycle • If the bean is just your raw object it is simply invoked directly (nothing special) TransferServiceImpl transfer(“$50”, “1”, 2”) transfer(“$50”, “1”, 2”) TransferServiceImpl • If your bean has been wrapped in a proxy things get more interesting Spring Proxy
  • 86. 86 Ramkrishna IT Systems 45 Inside The Bean Request (Use) Lifecycle • If the bean is just your raw object it is simply invoked directly (nothing special) TransferServiceImpl transfer(“$50”, “1”, 2”) transfer(“$50”, “1”, 2”) TransferServiceImpl • If your bean has been wrapped in a proxy things get more interesting Spring Proxy
  • 87. 87 Ramkrishna IT Systems 45 TransferServiceImpl transfer(“$50”, “1”, 2”) transfer(“$50”, “1”, 2”) TransferServiceImpl • If your bean has been wrapped in a proxy things get more interesting Spring Proxy
  • 88. 88 Ramkrishna IT Systems Annotation-Based Dependency Injection Introducing Spring’s Annotations for Dependency Injection
  • 89. 89 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 90. 90 Ramkrishna IT Systems Configuration Instructions How Spring Works Your Application Classes (POJOs) Spring Application Context Creates Fully configured application system Ready for use
  • 91. 91 Ramkrishna IT Systems The Approach You’re Used to public class TransferServiceImpl implements TransferService { public TransferServiceImpl(AccountRepository ar) { this.accountRepository = ar; } … } public class JdbcAccountRepository implements AccountRepository { public void setDataSource(DataSource ds) { this.dataSource = ds; } … } 4 Use POJOs with constructor arguments and/or property setters for configuration
  • 92. 92 Ramkrishna IT Systems The Approach You’re Used to <beans> <bean id=“transferService” class=“app.impl.TransferServiceImpl””> <constructor-arg ref=“accountRepository” /> </bean> <bean id=“accountRepository” class=“app.impl.JdbcAccountRepository””> <property name=“dataSource” ref=“dataSource” /> </bean> <bean id=“dataSource” class=“com.oracle.jdbc.pool.OracleDataSource””> <property name=“URL” value=“jdbc:oracle:thin:@localhost:1521:BANK” /> <property name=“user” value=“moneytransfer-app” /> </bean> </beans> 5 <bean> defines a bean Dependency Injection
  • 93. 93 Ramkrishna IT Systems Alternative Approaches • Bean definitions can also be defined and configured in Java • Or by using annotations in Spring-managed classes • Both are alternatives to XML approach – Not intended as complete replacements – Can be used together
  • 94. 94 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 95. 95 Ramkrishna IT Systems Java-based Approach • Spring 3.0 introduces Java-based configuration – Based on the old JavaConfig project • Use Java code to define and configure beans – Configuration still external to POJO classes to be configured – More control over bean instantiation and configuration – More type-safety • Still produces bean definitions – Spring remains in charge applying post-processors etc.
  • 96. 96 Ramkrishna IT Systems •The central artifact in Spring's new Java-configuration support is the @Configuration-annotated class. •These classes consist principally of @Bean-annotated methods •These Methods define instantiation, configuration, and initialization logic for objects to be managed by the Spring IoC container. •Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } <beans> <bean id="myService" class=“com.rits.training.MyServiceImpl"/> </beans> XML Way Spring3.0 Java Configuration Class
  • 97. 97 Ramkrishna IT Systems @Configuration-annotated classes are sub-classed at load time by CGLIB so They should not be final They should have no-arg non-private constructor @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } Getting bean instances using AnnotationConfigApplicationContext. Class client{ public static void main(String[] args){ AnnotationConfigApplicationContext ctx = new AnnotaionConfigApplicationContext(AppConfig.class) } Spring3.0 Java Configuration Class No XML Just Use @Configuration class Name
  • 98. 98 Ramkrishna IT Systems @Mix-Match of Java-Based and XML based configuration (@Configuration –centric) @ImportResource("test-infrastructure-Java_Based_config.xml") public class BankConfig { private @Value(“#{jdbcProperties.oracleURL}") String url; private @Value(“#{jdbcProperties.oracleUser}") String username; private @Value(“#{jdbcProperties.oraclePassword}") String password; private @Value(“#{jdbcProperties.oracleDriver}") String driver; ….. public @Bean(scope=“singleton”) DriverManagerDataSource dataSource() { return new DriverManagerDataSource(url, username, password); } testdb.properties oracleDriver=oracle.jdbc.driver.OracleDriver oracleURL=jdbc:oracle:thin:@localhost:1521:XE oracleUser=system oraclePassword=system Spring3.0 Java Configuration Class <util:properties id="jdbcProperties" location="testdb.properties"/> test-infrastructure-…xml
  • 99. 99 Ramkrishna IT Systems @Configuration("configBank") @ImportResource("test-infrastructure-Java_Based_config.xml") public class BankConfig { private @Value("#{jdbcProperties.oracleURL}") String url; private @Value("#{jdbcProperties.oracleUser}") String username; ….. @Bean(name="bankService") @Scope("prototype") Bank bankService(){ Collection<AccountService> accts = new ArrayList<AccountService>(); accts.add(currentAccount()); accts.add(loan()); accts.add(saving()); return new BankImpl(accountRepository(),accts); } @Bean(name="acctRepo") AccountRepository accountRepository(){ return new AccountRepositoryImpl(dataSource()); } @Bean(name="current") AccountService currentAccount(){ CurentAccount acct= new CurentAccount("Ramkrishna IT",1000000); acct.setAcctNo(123456789); return acct; } public @Bean DriverManagerDataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(url, username, password); dataSource.setDriverClassName(driverClassName); return dataSource; } }
  • 100. 100 Ramkrishna IT Systems Enabling Java-based Approach • Making this work requires two steps: – Define config class as Spring Bean – Add <context:annotation-config/> <beans xmlns="http://www.springframework.org/schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="..."> <context:annotation-config/> Turns on checking of configuration annotations for beans declared in this context
  • 101. 101 Ramkrishna IT Systems Usage - Nothing Changes! // Create the application from the configuration ApplicationContext context = new ClassPathXmlApplicationContext(“application-config.xml””); // Look up the application service interface Bank service = (Bank) context.getBean(“bankService””); // Use the application
  • 102. 102 Ramkrishna IT Systems Implementing @Bean Methods • Configuration in Java: call any code you want – Not just constructors and property setters • May not be private • Method name becomes bean name • Call @Bean method to refer to bean in same class – We'll show how to refer to external beans later • Same defaults as XML: beans are singletons – Use @Scope annotation to change scope @Bean @Scope("prototype") public StatefulService service() { …
  • 103. 103 Ramkrishna IT Systems @Bean Lifecycle • Init- and destroy methods can be specified – Using attributes of the annotation – init really isn't required, can just call method yourself @Bean(destroyMethod="close") public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl("jdbc:derby:rewardsdb"); // can call init method here if you need to return dataSource; }
  • 104. 104 Ramkrishna IT Systems Implementing @Configuration Classes • Must have default constructor • Multiple @Configuration classes may exist • Can import each other using @Import – Equivalent to <import/> in XML – Means included classes don't have to be defined as Spring beans anymore @Import({SecurityConfig.class, JmxConfig.class}) @Configuration public class RewardsConfig { … }
  • 105. 105 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 106. 106 Ramkrishna IT Systems Annotation-based Configuration • Spring 2.5 introduced annotation-based configuration as another alternative to XML • Moves configuration instructions into your code – Unlike XML or Java-based approaches • Can be used in combination with the other approaches Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.
  • 107. 107 Ramkrishna IT Systems The Annotation-Based Approach public class TransferServiceImpl implements TransferService { @Autowired public TransferServiceImpl(AccountRepository ar) { this.accountRepository = ar; } … public class JdbcAccountRepository implements AccountRepository { @Autowired public void setDataSource(DataSource ds) { this.dataSource = ds;} … } 17 Spring automatically tries to wire this }
  • 108. 108 Ramkrishna IT Systems The Annotation-Based Approach <beans> <context:annotation-config/> <bean id=“transferService” class=“app.impl.TransferServiceImpl”/”/> <bean id=“accountRepository” class=“app.impl.JdbcAccountRepository””/> <bean id=“dataSource” class=“com.oracle.jdbc.pool.OracleDataSource””> <property name=“URL” value=“jdbc:oracle:thin:@localhost:1521:BANK” /> <property name=“user” value=“moneytransfer-app” /> </bean> </beans> 18 No need to specify constructor-arg or property
  • 109. 109 Ramkrishna IT Systems Quick Start Summary • Spring container needs POJOs and wiring instructions to assemble your application • Wiring instructions can be provided in XML… • …but also using Java with @Bean-methods • … or @Autowired annotations… • …or a combination
  • 110. 110 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 111. 111 Ramkrishna IT Systems Configuration Annotations • • • • • • @Autowired @Qualifier / @Primary @Resource @Value @Component / @Repository Shown already: – @Configuration / @Bean plus @Scope, @Import, etc. – @PostConstruct / @PreDestroy / @Required
  • 112. 112 Ramkrishna IT Systems @Autowired • Asks Spring to autowire fields, methods or constructors by using the type` – Requires unique match! • Removes the need to specify constructor-arg or property elements in XML` public class TransferServiceImpl implements TransferService @Autowired public TransferServiceImpl(AccountRepository ar) { this.accountRepository = ar; } … }
  • 113. 113 Ramkrishna IT Systems @Autowired • Methods can have any name • Methods and constructors can have multiple arguments that will all be injected public class MyServiceImpl implements MyService @Autowired public void initialize(SomeDependency sd, OtherDependency od) { this.someDependency = sd; this.otherDependency = od;} … }
  • 114. 114 Ramkrishna IT Systems Disambiguation with @Autowired • Disambiguation needed when multiple beans of same type exist, one of which must be injected • Using @Qualifier you can inject beans by name @Autowired @Qualifier(“primaryDataSource”) private DataSource dataSource; @Autowired void init(@Qualifier(“primaryDataSource”) DataSource primary, @Qualifier(“altDataSource”) DataSource alternative) { … } 24 Specify name of bean to inject
  • 115. 115 Ramkrishna IT Systems Option-I use qualifier child element in <bean> definition <bean class=“com.rits.SomeDBSource”> <qualifier value=“primaryDataSource” > </bean> <bean class=“com.rits.SomeOtherDBSource”> <qualifier value=“primaryDataSource” > </bean>
  • 116. 116 Ramkrishna IT Systems 25 Disambiguation with @Primary Option-II Java-based config alternative solution: one bean can be made the primary candidate for autowiring – Will be used in case of multiple matches by type @Bean @Primary public DataSource standardDataSource() { … } @Bean public DataSource backupDataSource() { … }
  • 117. 117 Ramkrishna IT Systems @Resource ("myBeanName") • • • • JSR-250 annotation (not Spring-specific) Injects a bean identified by the given name Useful when auto wiring by type does not work Can also lookup JNDI references public class TransferServiceImpl implements TransferService { @Resource("myBackupRepository") public void setBackupRepo(AccountRepository repo) { this.backRepo = repo; } } 26 Option-III
  • 118. 118 Ramkrishna IT Systems 27 @Resource in Spring Some additional behavior over Java EE 5: • By default, falls back to autowiring by type if no bean with given name exists • Works for all methods, not just setters – But not for constructors!
  • 119. 119 Ramkrishna IT Systems 28 SpEL and Annotations • Use @Value for SpEL expressions in Java code – On a field or method or on parameter of autowired method or constructor @Value("#{ systemProperties['user.region'] }") private String defaultLocale; @Value("#{ systemProperties['user.region'] }") public void setDefaultLocale(String defaultLocale) { … } @Autowired public void configure(AccountRepository accountRepository, @Value("#{ systemProperties['user.region'] }") String defaultLocale) { … }
  • 120. 120 Ramkrishna IT Systems <context:annotation-config/> Turns on checking of DI annotations for beans declared in this context <bean id=“transferService” class=“transfer.TransferService””/> <bean id=“accountRepository” class=“transfer.JdbcAccountRepository””/> </beans> 29 For these Annotations to Work… We need to ‘enable them’, just like for Java-based configuration <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="...">
  • 121. 121 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 122. 122 Ramkrishna IT Systems 31 @Component • Identifies POJOs as Spring Beans • Removes the need to specify almost anything in XML @Component public class TransferServiceImpl implements TransferService @Autowired public TransferServiceImpl(AccountRepository ar) { this.accountRepository = ar; } … }
  • 123. 123 Ramkrishna IT Systems 32 @Component and names • Default bean name is de-capitalized non-qualified name • @Component takes an optional String to name the bean – Arguably not a best practice to put bean names in your Java code ”)@Component(“transferService”) public class TransferServiceImpl implements TransferService @Autowired public TransferServiceImpl(AccountRepository ar) { this.accountRepository = ar; } … }
  • 124. 124 Ramkrishna IT Systems 33 For This Annotation To Work… • We need to enable ‘component scanning’ – Auto-enables <context:annotation-config/> <beans xmlns="http://www.springframework.org/schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package=“transfer””/> </beans> No more need to mention the beans in the application context
  • 125. 125 Ramkrishna IT Systems 34 @Scope and @Primary Like with @Bean: • @Scope allows customizing the instantiation strategy ”)@Scope(“prototype”) @Component public class TransferServiceImpl implements TransferService { … • @Primary allows making one component-scanned bean the primary candidate for autowiring @Primary @Component public class DefaultCalculationService implements CalculationService { …
  • 126. 126 Ramkrishna IT Systems 35 Scanning and auto-wiring for @Configuration classes • Are picked up by component scanning – No more need for XML bean definition or @Import • Can use autowiring – Like any Spring-bean – Gives access to external beans from @Bean methods • Can be autowired into another @Configuration – Allowing for external @Bean methods to be called – Type-safe, IDE-friendly alternative to by-name wiring
  • 127. 127 Ramkrishna IT Systems 36 Combined Example @Configuration public class InfraConfig { @Bean public DataSource dataSource() { DataSource dataSource = ...; return dataSource; } } @Configuration @Import(InfraConfig.class) public class RewardsConfig { @Autowired InfraConfig infraConfig; @Bean AccountRepository accountRepository() { JdbcAccountRepository repository = new JdbcAccountRepository(); repository.setDataSource(infraConfig.dataSource()); return repository; } } Import not needed if InfraConfig was component-scanned Alternative is to simply autowire DataSource directly
  • 128. 128 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 129. 129 Ramkrishna IT Systems 38 Stereotype annotations • Component scanning also checks for annotations that are themselves annotated with @Component – So-called stereotype annotations(Marker annotaion suggesting specific purpose – Identify the architectural purpose of a class – Particularly useful for matching (e.g. with AOP) • Spring framework stereotype annotations: – @Service – identify service classes – @Repository – identify data access classes – @Controller – identify web presentation classes • Other Spring-based frameworks define their own
  • 130. 130 Ramkrishna IT Systems 39 Meta-annotations • A meta-annotation is an annotation which can be used to annotate other annotations • e.g. all of your service beans should be configurable using component scanning and be transactional @Transactional(timeout=60) @Service @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyTransactionalService { String value() default ""; } @MyTransactionalService public class TransferServiceImpl implements TransferService { ...
  • 131. 131 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 132. 132 Ramkrishna IT Systems 41 When use what? Annotations: • Nice for frequently changing beans – Start using for small isolated parts of your application (e.g. Spring @MVC controllers) • Pros: – Single place to edit (just the class) – Allows for very rapid development • Cons: – Configuration spread across your code base – Only works for your own code --Maintenance issues --Recompilation for any changes
  • 133. 133 Ramkrishna IT Systems When use what? XML: • Cons: – Some people just don't like XML... • For infrastructure and more 'static' beans • Pros: – Is centralized in one (or a few) places – Most familiar configuration format for most people – Can be used for all classes (not just your own)
  • 134. 134 Ramkrishna IT Systems 43 When use what? Java-based: • For full control over instantiation and configuration – As alternative to implementing FactoryBean • Pros: – Configuration still external to code – Integrates well with legacy code • Can call methods such as addDataSource(DataSource d) • Cons: – Wiring won't show up in STS – No equivalent to the XML namespaces
  • 135. 135 Ramkrishna IT Systems Topics in this Session • • • • • • • • • Configuration Approaches Java-based Configuration Annotation Quick Start Other Configuration Annotations Component Scanning Stereotype and Meta-annotations When To Use What Summary & Lab Advanced Options
  • 136. 136 Ramkrishna IT Systems 45 Summary • Spring’s configuration directives can be written in XML, using Java or using annotations • You can mix and match XML, Java and annotations as you please • Autowiring with @Component or @Configuration allows for almost empty XML configuration files
  • 137. 137 Ramkrishna IT Systems Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. LAB Using Spring’s annotations to Configure and test an application
  • 138. 138 Ramkrishna IT Systems AOP •Aspect Oriented Programming Cross-Cutting Concerns : Transactions, Logging, Security, Caching, ErrorHandling Goal : Separation of cross-cutting concerns from business logic Write common functionality at one place Declaratively add the functionality in the code Decoupling business domain logic from infrastructure code No impact on adding or removing the infra functionality.
  • 139. 139 Ramkrishna IT Systems AOP •Aspect Oriented Programming Cross-Cutting Concerns : Transactions, Logging, Security, Caching, ErrorHandling Goal : Separation of cross-cutting concerns from business logic Write common functionality at one place Declaratively add the functionality in the code Decoupling business domain logic from infrastructure code No impact on domain code while adding/removing the infra.
  • 140. 140 Ramkrishna IT Systems AOP •Aspect Oriented Programming Goal : To Avoid Code Tangling(Mixing of concerns) To avoid Code scattering(Duplication of code at multiple places)
  • 141. 141 Ramkrishna IT Systems 6 Implementing Cross Cutting Concerns Without Modularization • Failing to modularize cross-cutting concerns leads to two things 1. Code tangling • A coupling of concerns 2. Code scattering • The same concern spread across modules
  • 142. 142 Ramkrishna IT Systems 7 Symptom #1: Tangling public class RewardNetworkImpl implements RewardNetwork { public RewardConfirmation rewardAccountFor(Dining dining) { if (!hasPermission(SecurityContext.getPrincipal()) { throw new AccessDeniedException(); } Account a = accountRepository.findByCreditCard(… Restaurant r = restaurantRepository.findByMerchantNumber(… MonetaryAmount amt = r.calculateBenefitFor(account, dining); … } } Mixed Concerns
  • 143. 143 Ramkrishna IT Systems Duplication 8 Symptom #2: Scattering public class HibernateAccountManager implements AccountManager { public Account getAccountForEditing(Long id) { if (!hasPermission(SecurityContext.getPrincipal()) { throw new AccessDeniedException(); } … public class HibernateMerchantReportingService implements MerchantReportingService { public List<DiningSummary> findDinings(String merchantNumber, DateInterval interval) { if (!hasPermission(SecurityContext.getPrincipal()) { throw new AccessDeniedException(); } …
  • 144. 144 Ramkrishna IT Systems BankService System Evolution Without Modularization Code tangling Security Transactions Logging CustomerService ReportingService Code scattering
  • 145. 145 Ramkrishna IT Systems How AOP Works 1. Implement your mainline application logic Focusing on the core problem 2. Write aspects to implement your cross-cutting concerns Spring provides many aspects out-of-the-box 3. Weave the aspects into your application Adding the cross-cutting behaviours to the right places
  • 146. 146 Ramkrishna IT Systems System Evolution: AOP based BankService Security Aspect CustomerService Transaction Aspect ReportingService Logging Aspect
  • 147. 147 Ramkrishna IT Systems 13 Leading AOP Technologies • AspectJ – Original AOP technology (first version in 1995) – Offers a full-blown Aspect Oriented Programming language • Uses byte code modification for aspect weaving • Spring AOP – Java-based AOP framework with AspectJ integration • Uses dynamic proxies for aspect weaving – Focuses on using AOP to solve enterprise problems – The focus of this session
  • 148. 148 Ramkrishna IT Systems 14 Topics in this session • • • • • • What Problem Does AOP Solve? Core AOP Concepts Quick Start Defining Pointcuts Implementing Advice Advanced topics – Named Pointcuts – Context selecting pointcuts – Working with annotations
  • 149. 149 Ramkrishna IT Systems Core AOP Concepts •Aspect Oriented Programming : Terminology Advice : A piece of code that needs to be executed before/after/around business logic. This code executes without knowledge of domain code. What and when is defined by advice Should it be applied before the method (Before advice) Should it be applied after method execution (After-return advice) Should it be applied before and after method (Around advice) Should it be applied if method throws an exception(After-throwing) Should it be applied after method execution (even if method throws exception) (After advice)
  • 150. 150 Ramkrishna IT Systems AOP •Aspect Oriented Programming : Terminology JoinPoint : • A join-point is a point in the execution of application where a particular cross-cutting concern (advice) is to be plugged-in • A JoinPoint could be a method invocation, a change of a field value or it could be an exception being thrown • Spring only supports method invocation as a JoinPoint
  • 151. 151 Ramkrishna IT Systems AOP •Aspect Oriented Programming : Terminology PointCut : • Its an expression which decides the set of JoinPoints where the advice is to applied. •Advices define when and what is to be applied while PointCut defines where it is to be applied. •PointCuts in Spring define set of methods using regular expressions.
  • 152. 152 Ramkrishna IT Systems AOP •Aspect Oriented Programming : Terminology •Aspect : • Aspect is combination of JoinPoints and PointCuts and advice Introduction : • It allows you to add new methods or attributes to existing classes without changing them
  • 153. 153 Ramkrishna IT Systems AOP •Aspect Oriented Programming : Terminology •Target : • Object on which advice is to applied Proxy : • A new Object which wraps the target object and intercepts the calls from the Client. •Proxy is the Object which will be created at runtime and it intercepts the invocations.
  • 154. 154 Ramkrishna IT Systems AOP •Aspect Oriented Programming : Terminology •Weaving : • Process of applying aspects on target objects •Weaving in Spring happens at runtime Proxy : • A new Object which wraps the target object and intercepts the calls from the Client. •Proxy is the Object which will be created at runtime and it intercepts the invocations.
  • 155. 155 Ramkrishna IT Systems Steps to Use AOP 1. Implement your mainline application logic Focusing on the core problem 2. Write aspects to implement your cross-cutting concerns • Spring provides many aspects out-of-the-box 3. Weave the aspects into your application • Adding the cross-cutting behaviours to the right places
  • 156. 156 Ramkrishna IT Systems AOP Quick Start • Consider this basic requirement • How can you use AOP to meet it? Log a message every time a property is about to change
  • 157. 157 Ramkrishna IT Systems Target Object : Whose State Change is to be tracked public class SimpleCache implements Cache { private int cacheSize; private DataSource dataSource; private String name; public void setCacheSize(int size) { cacheSize = size; } public void setDataSource(DataSource ds) { dataSource = ds; } public void setBeanName(String beanName) { name = beanName; } public String toString() { return name; } … }
  • 158. 158 Ramkrishna IT Systems Implement the Aspect @Aspect public class PropertyChangeTracker { private Logger logger = Logger.getLogger(getClass()); @Before(“execution(void set*(*))”) public void trackChange() { logger.info(“Property about to change…”); } }
  • 159. 159 Ramkrishna IT Systems <beans> <aop:aspectj-autoproxy> <aop:include name=“propertyChangeTracker” /> </aop:aspectj-autoproxy> <bean id=“propertyChangeTracker” class=“example.PropertyChangeTracker” /> </beans> 20 Configures Spring to apply the @Aspect to your beans Configure the Aspect as a Bean aspects-config.xml
  • 160. 160 Ramkrishna IT Systems Include the Aspect Configuration <beans> <import resource= “aspects-config.xml”/> <bean name=“cache-A” class=“example.SimpleCache” ../> <bean name=“cache-B” class=“example.SimpleCache” ../> <bean name=“cache-C” class=“example.SimpleCache” ../> </beans> application-config.xml
  • 161. 161 Ramkrishna IT Systems Test the Application ApplicationContext context = new ClassPathXmlApplicationContext(“application-config.xml”); Cache cache = (Cache) context.getBean(“cache-A”); cache.setCacheSize(2500); INFO: Property about to change…
  • 162. 162 Ramkrishna IT Systems SimpleCache (target) PropertyChange Tracker (aspect) 4. Matching advice is executed 1. Spring creates a proxy that brings the aspect and target together 23 3. All calls routed through proxy Spring AOP Proxy (this) <<interface>> Cache the business interface of the target How Aspects are Applied 2. The proxy implements setCacheSize(2500)
  • 163. 163 Ramkrishna IT Systems } } Tracking Property Changes – With Context • Context is provided by the JoinPoint method parameter @Aspect public class PropertyChangeTracker { private Logger logger = Logger.getLogger(getClass()); Context about the intercepted point @Before(“execution(void set*(*))”) public void trackChange(JoinPoint point) { String name = point.getSignature().getName(); Object newValue = point.getArgs()[0]; logger.info(name + “ about to change to ” + newValue + “ on ” + point.getTarget()); INFO: setCacheSize about to change to 2500 on cache-A
  • 164. 164 Ramkrishna IT Systems Topics in this session • • • • • • What Problem Does AOP Solve? Core AOP Concepts Quick Start Defining Pointcuts Implementing Advice Advanced topics – Named Pointcuts – Context selecting pointcuts – Working with annotations
  • 165. 165 Ramkrishna IT Systems Defining Pointcuts • With Spring AOP you write pointcuts using AspectJ’s pointcut expression language – For selecting where to apply advice • Complete expression language reference available at – http://www.eclipse.org/aspectj
  • 166. 166 Ramkrishna IT Systems Common Pointcut Designator • execution(<method pattern>) – The method must match the pattern • Can chain together to create composite pointcuts – && (and), || (or), ! (not) – [Modifiers] ReturnType [ClassType] MethodName ([Arguments]) [throws ExceptionType]
  • 167. 167 Ramkrishna IT Systems Writing expressions execution(* rewards.restaurant.*Service.find*(..)) package type params methoddesignator return type
  • 168. 168 Ramkrishna IT Systems 29 Execution Expression Examples execution(void send*(String)) – Any method starting with send that takes a single String parameter and has a void return type execution(* send(*)) – Any method named send that takes a single parameter execution(* send(int, ..)) – Any method named send whose first parameter is an int (the “..” signifies 0 or more parameters may follow)
  • 169. 169 Ramkrishna IT Systems 30 Execution Expression Examples execution(void example.MessageServiceImpl.*(..)) – Any visible void method in the MessageServiceImpl class execution(void example.MessageService+.send(*)) – Any void method named send in any object of type MessageService (that include possible child classes or implementors of MessageService) execution(@javax.annotation.security.RolesAllowed void send*(..)) – Any void method starting with send that is annotated with the @RolesAllowed annotation
  • 170. 170 Ramkrishna IT Systems 31 Execution Expression Examples working with packages execution(* rewards.*.restaurant.*.*(..)) – There is one directory between rewards and restaurant execution(* rewards..restaurant.*.*(..)) – There may be several directories between rewards and restaurant execution(* *..restaurant.*.*(..)) – Any sub-package called restaurant
  • 171. 171 Ramkrishna IT Systems Proxy BeforeAdvice Target Before Advice
  • 172. 172 Ramkrishna IT Systems Before Advice Example • Use @Before annotation – If the advice throws an exception, target will not be called @Aspect public class PropertyChangeTracker { private Logger logger = Logger.getLogger(getClass()); @Before(“execution(void set*(*))”) public void trackChange() { logger.info(“Property about to change…”); } } Track calls to all setter methods
  • 173. 173 Ramkrishna IT Systems After Advice Proxy AfterReturning Target Successful return
  • 174. 174 Ramkrishna IT Systems After Returning • @Aspect • public class PropertyChangeTracker { • @Pointcut(" execution(* update*(..)) || execution(* set*(..))") • void updateORSetMethod(){} • @Pointcut("(!execution(* bank.server.internal.BankImpl.get*(*))) && execution(* get*(..))") • void getMethodAdvice(){} • @After("updateORSetMethod()") • void trackChange2(JoinPoint jp){ • String methodName = jp.getSignature().getName(); • Object newValue = jp.getArgs()[0]; • System.out.println("After Advice of PropertyChangeTracker1 invoked for method "+methodName); • System.out.println("After 1 Property changed to "+newValue); • } • }
  • 175. 175 Ramkrishna IT Systems After Advice Proxy After Advice Target Success or Exception
  • 176. 176 Ramkrishna IT Systems AfterThrowing Advice Proxy After Advice Target Exception
  • 177. 177 Ramkrishna IT Systems After Throwing • @Aspect • public class PropertyChangeTracker { • @Pointcut(" execution(* update*(..)) || execution(* set*(..))") • void updateORSetMethod(){} • @Pointcut("(!execution(* bank.server.internal.BankImpl.get*(*))) && execution(* get*(..))") • void getMethodAdvice(){} • @After("updateORSetMethod()") • @AfterThrowing(value="getMethodAdvice()",throwing="e") • void handleException(JoinPoint p, Throwable e){ • System.out.println("DEBUG AfterThrowing invoked due ot Exception "+e.getMessage()+"By method "+p.getSignature().getName()+" On Class "+p.getTarget().getClass().getName()); • } • }
  • 178. 178 Ramkrishna IT Systems Around Advice Around TargetProxyProxy Around Target proceed() Around Advice
  • 179. 179 Ramkrishna IT Systems @Around • @Aspect • public class PropertyChangeTracker { • @Around("! execution(* bank.server.internal.BankImpl.get*(*)) && (execution(* update*(..)) || execution(* set*(..))|| execution(* get*(..)))" ) • Object trackChange(ProceedingJoinPoint jp) throws Throwable{ – String methodName = jp.getSignature().getName(); • Object newValue =null; – if(jp.getArgs().length>0){ – newValue = jp.getArgs()[0]; – } – System.out.println("Kind ="+jp.getKind()); – System.out.println("PropertyChangeTracker FIRST invoked for method "+methodName); – System.out.println("BEFORE Property Change About to change to "+newValue); – Object value = jp.proceed(); – System.out.println("AROUND AFTER property change is complete value ="+value); – if(value instanceof String) – return value+"CHANGED BY ADVICE"; – return value; • }} }
  • 181. 181 Ramkrishna IT Systems 44 Alternative Spring AOP Syntax - XML • Annotation syntax is Java 5+ only • XML syntax works on Java 1.4 • Approach – Aspect logic defined Java – Aspect configuration in XML • Uses the aop namespace
  • 182. 182 Ramkrishna IT Systems 45 Tracking Property Changes - Java Code public class PropertyChangeTracker { public void trackChange(JoinPoint point) { … } } Aspect is a Plain Java Class with no Java 5 annotations
  • 183. 183 Ramkrishna IT Systems 46 Tracking Property Changes - XML Configuration <aop:config> <aop:aspect ref=“propertyChangeTracker”> <aop:before pointcut=“execution(void set*(*))” method=“trackChange”/> </aop:aspect> </aop:config> <bean id=“propertyChangeTracker” class=“example.PropertyChangeTracker” /> • XML configuration uses the aop namespace
  • 184. 184 Ramkrishna IT Systems 48 Topics in this session • • • • • • What Problem Does AOP Solve? Core AOP Concepts Quick Start Defining Pointcuts Implementing Advice Advanced topics – – – – Named Pointcuts Context selecting pointcuts Working with annotations Limitations of Spring AOP
  • 185. 185 Ramkrishna IT Systems 49 • Allow to reuse and combine pointcuts @Aspect public class PropertyChangeTracker { private Logger logger = Logger.getLogger(getClass()); @Before(“serviceMethod() || repositoryMethod()”) public void monitor() { logger.info(“A business method has been accessed…”); } @Pointcut(“execution(* rewards.service..*Service.*(..))”) public void serviceMethod() {} @Pointcut(“execution(* rewards.repository..*Repository.*(..))”) public void repositoryMethod() {} } Named pointcuts
  • 186. 186 Ramkrishna IT Systems } } Named pointcuts • Expressions can be externalized public class SystemArchitecture { @Pointcut(“execution(* rewards.service..*Service.*(..))”) public void serviceMethods() {} } @Aspect public class ServiceMethodInvocationMonitor { private Logger logger = Logger.getLogger(getClass()); @Before(“com.acme.SystemArchitecture.serviceMethods()” ) public void monitor() { logger.info(“A service method has been accessed…”); Fully-qualified pointcut name 50
  • 187. 187 Ramkrishna IT Systems 51 • Give the possibility to break one complicated expression into several sub-expressions • Allow pointcut expression reusability • Best practice: consider externalizing expressions into one dedicated class – When working with many pointcuts – When writing complicated expressions Named pointcuts - Summary
  • 188. 188 Ramkrishna IT Systems 52 Topics in this session • • • • • • What Problem Does AOP Solve? Core AOP Concepts Quick Start Defining Pointcuts Implementing Advice Advanced topics – – – – Named Pointcuts Context selecting pointcuts Working with annotations Limitations of Spring AOP
  • 189. 189 Ramkrishna IT Systems Context Selecting Pointcuts • Pointcuts may also select useful join point context – – – – The currently executing object (proxy) The target object Method arguments Annotations associated with the method, target, or arguments • Allows for simple POJO advice methods – Alternative to working with a JoinPoint object directly 53
  • 190. 190 Ramkrishna IT Systems Context Selecting Example • Consider this basic requirement Log a message every time Server is about to start public interface Server { public void start(Map input); public void stop(); } In the advice, how do we access Server? Map? 54
  • 191. 191 Ramkrishna IT Systems 55 Without context selection @Before(“execution(void example.Server+.start(java.util.Map))”) public void logServerStartup(JoinPoint jp) { Server server = (Server) jp.getTarget(); Object[] args= jp.getArgs(); Map map = (Map) args[0]; … } • All needed info must be obtained from the JoinPoint object
  • 192. 192 Ramkrishna IT Systems 56 With context selection @Before(“execution(void example.Server+.start(java.util.Map)) && target(server) && args(input)”) public void logServerStartup(Server server, Map input) { … } • Best practice: use context selection – Method attributes are bound automatically - target(server) selects the target of the execution (your object) - this(server) would have selected the proxy
  • 193. 193 Ramkrishna IT Systems Context Selection - Named Pointcut @Before(“serverStartMethod(server, input)”) public void logServerStartup(Server server, Map input) { … } @Pointcut(“execution(void example.Server+.start(java.util.Map)) && target(server) && args(input)”) public void serverStartMethod (Server server, Map input) {} 57 ‘target’ binds the server starting up ‘args’ binds the argument value
  • 194. 194 Ramkrishna IT Systems 58 Topics in this session • • • • • • What Problem Does AOP Solve? Core AOP Concepts Quick Start Defining Pointcuts Implementing Advice Advanced topics – – – – Named Pointcuts Context selecting pointcuts Working with annotations Limitations of Spring AOP
  • 195. 195 Ramkrishna IT Systems 59 Pointcut expression examples using annotations • execution( @org.springframework.transaction.annotation.Transactional void *(..)) – Any method marked with the @Transactional annotation • execution( (@example.Tracked *) *(..)) – Any method that returns a value marked with the @Tracked annotation
  • 196. 196 Ramkrishna IT Systems @Secured(allowedRoles={“teller”,”manager”}) public void waiveFee () { … } 60 Example Requirements: Run a security check before any @Secured service operation Security logic depends on: ∉ ∉ ∉ annotation attribute value – what roles to check? method name – what method is protected? the ‘this’ object – Spring AOP proxy being protected
  • 197. 197 Ramkrishna IT Systems 61 AOP and annotations - Example @Before(“execution(* service..*.*(..)) && target(object) && @annotation(secured)””)) public void runCheck(JoinPoint jp, Object object, Secured secured) { checkPermission(jp, object, secured.allowedRoles()); } Run a security check before any @Secured service operation • Use of the annotation() designator
  • 198. 198 Ramkrishna IT Systems 62 AOP and annotations – Named pointcuts @Before(“securedMethod(object, secured)””) public void runCheck(JoinPoint jp, Object object, Secured secured) { checkPermission(jp, object, secured.allowedRoles()); } @Pointcut((“execution(* service..*.*(..)) && target(object) && @annotation(secured)””)) public void securedMethod(Object object, Secured secured) {} Run a security check before any @Secured service operation
  • 199. 199 Ramkrishna IT Systems 63 Topics in this session • • • • • • What Problem Does AOP Solve? Core AOP Concepts Quick Start Defining Pointcuts Implementing Advice Advanced topics – – – – Named Pointcuts Context selecting pointcuts Working with annotations Limitations of Spring AOP
  • 200. 200 Ramkrishna IT Systems 64 Limitations of Spring AOP • Can only advise public Join Points • Can only apply aspects to Spring beans • Some limitations of weaving with proxies – Spring will add behavior using dynamic proxies if a Join Point is declared on an interface – If a Join Point is in a class without an interface, Spring will revert to using CGLIB for weaving – When using proxies, if method a() calls method b() on the same class/interface, advice will never be executed for method b()
  • 201. 201 Ramkrishna IT Systems 65 Summary • Aspect Oriented Programming (AOP) modularizes cross-cutting concerns • An aspect is a module containing cross- cutting behavior – Behavior is implemented as “advice” – Pointcuts select where advice applies – Five advice types: Before, AfterThrowing, AfterReturning, After and Around • Aspects are defined in Java with annotations or XML configuration
  • 202. 202 Ramkrishna IT Systems 48 LAB : Advance AOP
  • 203. 203 Ramkrishna IT Systems Data Access Using Spring • Resource Management : – Creating Connection Pools – Acquiring and releasing connections from/to the pool – Closing connections – Demarcation of transaction – Commit or rollback of transaction – Iterating through ResultSet and creating JavaObjects – Checking ErrorCodes and mapping exceptions to meaningful messages – Checking Exception state and mapping it to meaningful messages All the concerns listed above is a job of application developer. Spring takes it away from developer.
  • 204. 204 Ramkrishna IT Systems Not Effective - Copy & Pasting Code doSomeWork(...) { try { get connection begin transaction execute SQL process the result set commit } catch (SQLException e) { rollback }throw application exception } finally { try { close connection } catch {} } Unique Copied around everywhere
  • 205. 205 Ramkrishna IT Systems Spring Features for resource Management • Declarative transaction management – Transactional boundaries declared via configuration – Enforced by a Spring transaction manager • Automatic connection management – Connections acquired/released automatically – No possibility of resource leak • Intelligent exception handling – Root cause failures always reported – Resources always released properly
  • 206. 206 Ramkrishna IT Systems Spring Resource Management doSomeWork(..) { try { establish connection begin transaction execute SQL process the result set commit } catch (SQLException) { rollback throw application exception } finally { try { close connection } catch {} } BEFORE
  • 207. 207 Ramkrishna IT Systems After Spring Resource Management @Transactional doSomeWork(..) { execute SQL process the result set }
  • 208. 208 Ramkrishna IT Systems Spring Resource Management Works Everywhere • Works consistently with all leading data access technologies – – – – – Java Database Connectivity (JDBC) JBoss Hibernate Java Persistence API (JPA) EclipseLink Apache iBatis • In any environment – Local (standalone app, web app) – Full-blown JEE container 17
  • 209. 209 Ramkrishna IT Systems Service Repository TransactionManager DataSource Connection (input) findDomainObject(criteria) select data domainObject mapObject(ResultSet) get connection new begin transaction transaction A Typical Application invocation sequence
  • 210. 210 Ramkrishna IT Systems Declarative Transaction Management • Spring adds the transaction management calls around your service logic • You simply declare the transactional policies and Spring enforces them
  • 211. 211 Ramkrishna IT Systems Setting Transactional Policies Declaratively public void invoke(…) { // your application logic } } Tells Spring to always run this method in a database transaction public class ServiceImpl implements ServiceInterface { @Transactional
  • 212. 212 Ramkrishna IT Systems Spring TransactionInterceptor begin commit TransactionManager ServiceImpl Transaction management behavior is added around your code invoke(input) You can change transaction managers without affecting your Application Code Enforcing Declarative Transactional Policies Spring AOP Proxy
  • 213. 213 Ramkrishna IT Systems Effects on Connection Management • Connections are managed for you – Driven by transactional boundaries – Not the responsibility of application code – No possibility of connection leak • Repositories always use the transactional connection for data access – Spring provides several ways to ensure this
  • 214. 214 Ramkrishna IT Systems Local Hibernate Configuration RewardNetworkImpl Hibernate AccountRepository Hibernate RestaurantRepository JdbcRewardRepository SessionFactory Hibernate TransactionManager BasicDataSource LocalSession FactoryBean creates
  • 215. 215 Ramkrishna IT Systems Introduction to Spring JDBC Simplifying JDBC-based data access with Spring JDBC
  • 216. 216 Ramkrishna IT Systems Topics in this Session • Problems with traditional JDBC – Results in redundant, error prone code – Leads to poor exception handling • Spring’s JdbcTemplate Configuration Query execution Working with result sets Exception handling • JDBC Namespace 2
  • 217. 217 Ramkrishna IT Systems Redundant, Error Prone Code public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = “select first_name, age from PERSON where last_name=?“; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString(”first_name“); int age = rs.getInt(“age”); personList.add(new Person(firstName, lastName, age)); } catch (SQLException e) { /* ??? */ } finally { conn.close(); } catch (SQLException e) { /* ??? */ } return personList;
  • 218. 218 Ramkrishna IT Systems Redundant, Error Prone Code public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = "select first_name, age from PERSON where last_name=?"; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lastName); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString(“first_name”); int age = rs.getInt(“age”); personList.add(new Person(firstName, lastName, age)); } } catch (SQLException e) { /* ??? */ } finally { try { conn.close(); } catch (SQLException e) { /* ??? */ } } return personList; } 4 The bold matters - the rest is boilerplate
  • 219. 219 Ramkrishna IT Systems Exception Handling is poor public List findByLastName(String lastName) { List personList = new ArrayList(); Connection conn = null; String sql = “select first_name, age from PERSON where last_name=?“; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); ResultSet rs = ps.executeQuery(); while (rs.next()) { String firstName = rs.getString(”first_name“); int age = rs.getInt(“age”); personList.add(new Person(firstName, lastName, age)); } catch (SQLException e) { /* ??? */ } finally { conn.close(); } catch (SQLException e) { /* ??? */ } return personList; What can we do?
  • 220. 220 Ramkrishna IT Systems Spring’s JdbcTemplate • Greatly simplifies use of the JDBC API – Eliminates repetitive boilerplate code – Alleviates common causes of bugs – Handles SQLExceptions properly • Without sacrificing power – Provides full access to the standard JDBC constructs
  • 221. 221 Ramkrishna IT Systems Acquisition of the connection Participation in the transaction Execution of the statement Processing of the result set Handling any exceptions Release of the connection JdbcTemplate in a Nutshell int count = jdbcTemplate.queryForInt( “SELECT COUNT(*) FROM CUSTOMER””); All handled by Spring
  • 222. 222 Ramkrishna IT Systems Creating a JdbcTemplate • Requires a DataSource • Create a template once and re-use it – Do not create one for each use – Thread safe after construction JdbcTemplate template = new JdbcTemplate(dataSource);
  • 223. 223 Ramkrishna IT Systems When to use JdbcTemplate • Useful standalone – Anytime JDBC is needed – In utility or test code – To clean up messy legacy code • Useful for implementing a repository in a layered application – Also known as a data access object (DAO)
  • 224. 224 Ramkrishna IT Systems Implementing a JDBC-based Repository public class AccountRepositoryImpl implements AccountRepository { private JdbcTemplate jdbcTemplate; public AccountRepositoryImpl (JdbcTemplate template) { public int getAccountCount() { String sql = “select count(*) from Accounts”; return jdbcTemplate.queryForInt(sql); } this.jdbcTemplate = template; } DI in config file
  • 225. 225 Ramkrishna IT Systems <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${oracleDriver}" /> <property name="url" value="${oracleURL}" /> <property name="username" value="${oracleUser}" /> <property name="password" value="${oraclePassword}"></property> </bean> <bean class="bank.server.internal.AccountRepositoryImpl" > <constructor-arg name="dataSource" ref="dataSource" /> <constructor-arg name="jdbcTemplate" ref="jdbcTemplate" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" > <constructor-arg name="dataSource" ref="dataSource" /> </bean> JdbcTemplate Mapping in Config File
  • 226. 226 Ramkrishna IT Systems Querying with JdbcTemplate • JdbcTemplate can query for – types (int, long, String) – Generic Maps – Domain Objects
  • 227. 227 Ramkrishna IT Systems Querying for Simple Java Types (1) • Query with no bind variables public int getPersonCount() { String sql = “select count(*) from PERSON”; return jdbcTemplate.queryForInt(sql);
  • 228. 228 Ramkrishna IT Systems Querying With JdbcTemplate • Query with a bind variable – Note the use of a variable argument list private JdbcTemplate jdbcTemplate; public int getCountOfPersonsOlderThan(int age) { return jdbcTemplate.queryForInt( “select count(*) from PERSON where age > ?”, age); No need for new Object[] { new Integer(age) }
  • 229. 229 Ramkrishna IT Systems Generic Queries • JdbcTemplate can return each row of a ResultSet as a Map • When expecting a single row – Use queryForMap(..) • When expecting multiple rows – Use queryForList(..) • Useful for reporting, testing
  • 230. 230 Ramkrishna IT Systems Querying for Generic Maps (1) • Query for a single row • returns: Map { ID=1, FIRST_NAME=“John”, LAST_NAME=“Doe” } public Map getPersonInfo(int id) { String sql = “select * from PERSON where id=?”; return jdbcTemplate.queryForMap(sql, id); } A Map of [Column Name | Field Value ] pairs
  • 231. 231 Ramkrishna IT Systems Querying for Generic Maps (2) • Query for multiple rows • returns: List { 0 - Map { ID=1, FIRST_NAME=“Vivek”, LAST_NAME=“Kulkarni” } 1 - Map { ID=2, FIRST_NAME=“Ram”, LAST_NAME=“Joshi” } 2 - Map { ID=3, FIRST_NAME=“Subhash”, LAST_NAME=“Bose” } } public List getAllPersonInfo() { String sql = “select * from PERSON”; return jdbcTemplate.queryForList(sql); A List of Maps of [Column Name | Field Value ] pairs