spring ppt

Post on 08-Apr-2015

357 Views

Category:

Documents

3 Downloads

Preview:

Click to see full reader

TRANSCRIPT

SPRING SPRING PRESENTATIONPRESENTATION

-Vinod Prabha-Vinod Prabha

EJBEJB•Provides enterprise services – Remoting, Provides enterprise services – Remoting, Transaction, SecurityTransaction, Security•Provides a declarative programming model.Provides a declarative programming model.•Complex to learn, implementComplex to learn, implement•Unwanted overhead. No or all solution.Unwanted overhead. No or all solution.Complexity NOT proportional to complexity of Complexity NOT proportional to complexity of application. Many files involved (Bean, Home, application. Many files involved (Bean, Home, Component interface)Component interface)•Beans are technology coupled.Beans are technology coupled.•Beans can’t work without EJB container.Beans can’t work without EJB container.•Not promoting test driven development. Overhead Not promoting test driven development. Overhead of start/stop container.of start/stop container.•Heavy weight container.Heavy weight container.

Why SpringWhy Spring•Based on POJO. No (least) coupling to Based on POJO. No (least) coupling to technology.technology.

•No need to implement special interfaces or No need to implement special interfaces or classes, for writing a service.classes, for writing a service.

•Testing is easy. J2EE container is not Testing is easy. J2EE container is not required.required.

•Complexity is proportional to complexity of Complexity is proportional to complexity of application.application.

•No JNDI look up. Spring container is No JNDI look up. Spring container is responsible for resolving dependencies.responsible for resolving dependencies.

What is SpringWhat is Spring• Spring = POJO + DI + AOPSpring = POJO + DI + AOP

• Spring is an open source light weight Spring is an open source light weight framework container which support framework container which support Inversion of control and POJO based Inversion of control and POJO based development.development.

•Light weight – entire spring.jar is 2.7 MB.Light weight – entire spring.jar is 2.7 MB.

•Inversion of control – Objects need not Inversion of control – Objects need not worry about their dependencies. Container worry about their dependencies. Container will take care of that.will take care of that.

•AOP – Business logic is separated from AOP – Business logic is separated from system services.system services.

What is SpringWhat is Spring• Container – Spring manages the life cycle Container – Spring manages the life cycle of beans. Allow management through of beans. Allow management through configuration.configuration.

Spring ModulesSpring Modules• Core container – Contains BeanFactory, Core container – Contains BeanFactory, an implementation of Factory pattern.an implementation of Factory pattern.

•Application Context – Extends Application Context – Extends BeanFactory. Provides i18n, publish BeanFactory. Provides i18n, publish events, email, JNDI access, EJB events, email, JNDI access, EJB integration, remoting, scheduling, integration, remoting, scheduling, integration with Velocity, FreeMarker etc.integration with Velocity, FreeMarker etc.

•AOP – Spring AOP support is based on AOP – Spring AOP support is based on API defined by the API defined by the AOP Alliance. AOP Alliance. The The Spring AOP module also introduces Spring AOP module also introduces metadata programming to Spring.metadata programming to Spring.

Spring ModulesSpring Modules•JDBC abstraction and DAO – Abstract away the JDBC abstraction and DAO – Abstract away the JDBC boiler plate code, prevent problems due to JDBC boiler plate code, prevent problems due to failure of closing database resources. Provides failure of closing database resources. Provides exception layer over several db server error exception layer over several db server error messages.messages.•ORM integration – Provides hooks to ORM ORM integration – Provides hooks to ORM frameworks.frameworks.•Spring Web context module- Built above Spring Web context module- Built above application context module. Provide context for application context module. Provide context for web application. Integration support with Struts.web application. Integration support with Struts.•Spring MVC – An MVC framework for web Spring MVC – An MVC framework for web application.application.

Simple Spring exampleSimple Spring examplepublic class Main {public class Main { public static void main(String[] args) {public static void main(String[] args) {ClassPathResource resource = new ClassPathResource resource = new ClassPathResource("com/springtraining/di/ApClassPathResource("com/springtraining/di/ApplicationContext.xml");plicationContext.xml");XmlBeanFactory factory = new XmlBeanFactory factory = new XmlBeanFactory(resource);XmlBeanFactory(resource);Bean1 bean1 = Bean1 bean1 = (Bean1)factory.getBean("bean1"); (Bean1)factory.getBean("bean1"); System.out.println("Done.."+ System.out.println("Done.."+ bean1.toString());bean1.toString()); }}}}

Constructor InjectionConstructor Injection<beans><beans> <bean id="bean1" <bean id="bean1" class="com.springtraining.di2.Bean1">class="com.springtraining.di2.Bean1"> <constructor-arg><constructor-arg> <ref bean="childBean"/><ref bean="childBean"/> </constructor-arg></constructor-arg> </bean></bean> <bean id="childBean" <bean id="childBean" class="com.springtraining.di2.ChildBean"/>class="com.springtraining.di2.ChildBean"/></beans></beans>

Setter InjectionSetter Injection<beans><beans> <bean id="bean1" class="com.springtraining.di3.Bean1"><bean id="bean1" class="com.springtraining.di3.Bean1"> <property name="childBean"><property name="childBean"> <ref bean="childBean"/><ref bean="childBean"/> <!--<!-- <bean id="childBean" <bean id="childBean" class="com.springtraining.di3.ChildBean"/>class="com.springtraining.di3.ChildBean"/> -->--> </property></property> </bean></bean> <bean id="childBean" <bean id="childBean" class="com.springtraining.di3.ChildBean"/>class="com.springtraining.di3.ChildBean"/> </beans></beans>

IoCIoC• Control is being inverted.Control is being inverted.

• IoC and DI used interchangeably. But not IoC and DI used interchangeably. But not the same.the same.

• DI is one concrete example of IoC.DI is one concrete example of IoC.

• AOP is another.AOP is another.

• With IoC, Object will relinquish control With IoC, Object will relinquish control over some feature to the framework.over some feature to the framework.

• Object creation control is relinquished Object creation control is relinquished using DI.using DI.

• Aspect delegation using AOP.Aspect delegation using AOP.

Programming to Programming to InterfaceInterfacePublic class LoginServiceImpl {Public class LoginServiceImpl {

Boolean authenticate(LoginInfo loginInfo) {Boolean authenticate(LoginInfo loginInfo) {

LoginDaoImpl loginDaoImpl = new LoginDaoImpl loginDaoImpl = new LoginDaoImpl();LoginDaoImpl();

loginDaoImpl.getUserDetails(loginInfo);loginDaoImpl.getUserDetails(loginInfo);

……..

}}

}}

Programming to Programming to InterfaceInterfacePublic class LoginServiceImpl {Public class LoginServiceImpl {

Boolean authenticate(LoginInfo loginInfo) {Boolean authenticate(LoginInfo loginInfo) {

LoginDao loginDao = LoginDao loginDao = MyDaoFactaory.getLoginDao();MyDaoFactaory.getLoginDao();

loginDao.getUserDetails(loginInfo);loginDao.getUserDetails(loginInfo);

……..

}}

}}

Programming to Programming to InterfaceInterfacePublic class MyDaoFactory {Public class MyDaoFactory {

Public static LoginDao getLoginDao() {Public static LoginDao getLoginDao() {

Return new LoginDaoHibernateImpl();Return new LoginDaoHibernateImpl();

}}

}}

AOPAOP• Programming technique that promotes Programming technique that promotes

separation of concern.separation of concern.

• Component contains core functionality Component contains core functionality and System Services (logging, security, and System Services (logging, security, etc).etc).

• System Services are called cross cutting System Services are called cross cutting services.services.

• Without AOP -Without AOP -

-Components are littered with code that is -Components are littered with code that is not related to core functionality.not related to core functionality.

-Duplicate code.-Duplicate code.

AOP termsAOP terms•

BeanFactory vs. BeanFactory vs. ApplicationContextApplicationContext• ApplicationContext has more ApplicationContext has more

functionality. (Refer slide#)functionality. (Refer slide#)

• The only times you might consider using The only times you might consider using a BeanFactory are in circumstances a BeanFactory are in circumstances where resources are scarce, such as a where resources are scarce, such as a mobile device.mobile device.

ApplicationContext ApplicationContext implementationsimplementations• ClassPathXmlApplicationContext - ClassPathXmlApplicationContext -

treating context definition files as class treating context definition files as class path resources.path resources.

• FileSystemXmlApplicationContext - FileSystemXmlApplicationContext - Loads a context definition from an XML Loads a context definition from an XML file in the filesystem.file in the filesystem.

• XmlWebApplicationContext - Loads XmlWebApplicationContext - Loads context definitions from an XML file context definitions from an XML file contained within a web application.contained within a web application.

Bean life cycle in SpringBean life cycle in Spring1.1. InstantiateInstantiate2.2. Set properties (DI)Set properties (DI)3.3. BeanNameAware’s setBeanNameBeanNameAware’s setBeanName4.4. BeanFactoryAware’s setBeanFactoryBeanFactoryAware’s setBeanFactory5.5. ApplicationContexAware’s setApplicationContext (Not ApplicationContexAware’s setApplicationContext (Not

applicable for BeanFactory)applicable for BeanFactory)6.6. @PostConstruct method@PostConstruct method7.7. BeanPostProcessor’s PostProcessBeforeInitializationBeanPostProcessor’s PostProcessBeforeInitialization8.8. InitializingBean’s afterPropertiesSetInitializingBean’s afterPropertiesSet9.9. Custom init methodCustom init method10.10. BeanPostProcessor’s postProcessAfterInitializationBeanPostProcessor’s postProcessAfterInitialization

Life cycle codeLife cycle code<beans><beans> <bean id="bean1" <bean id="bean1"

class="com.springtraining.lifecycle.Bean1" class="com.springtraining.lifecycle.Bean1" init-method="customInit"/>init-method="customInit"/>

<bean id="bpp" <bean id="bpp" class="com.springtraining.lifecycle.MyBeanclass="com.springtraining.lifecycle.MyBeanPostProcessor"/>PostProcessor"/>

<bean <bean class="org.springframework.context.annotaticlass="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/on.CommonAnnotationBeanPostProcessor"/> >

</beans></beans>

Life cycle codeLife cycle codepublic class MyBeanPostProcessor implements public class MyBeanPostProcessor implements

BeanPostProcessor {BeanPostProcessor {

public Object postProcessBeforeInitialization(Object obj, public Object postProcessBeforeInitialization(Object obj, String arg1) throws BeansException {String arg1) throws BeansException {

System.out.println("postProcessBeforeInitialization");System.out.println("postProcessBeforeInitialization"); return obj;return obj; }}

public Object postProcessAfterInitialization(Object obj, String public Object postProcessAfterInitialization(Object obj, String arg1) throws BeansException {arg1) throws BeansException {

System.out.println("postProcessAfterInitialization");System.out.println("postProcessAfterInitialization"); Class clazz = obj.getClass();Class clazz = obj.getClass(); System.out.println("Proxying " + clazz.getName());System.out.println("Proxying " + clazz.getName()); return obj;return obj; }}}}

Life cycle codeLife cycle codepublic class Bean1 implements BeanNameAware, ApplicationContextAware, InitializingBean {public class Bean1 implements BeanNameAware, ApplicationContextAware, InitializingBean {

private String beanId;private String beanId;

public void customInit() {public void customInit() { System.out.println("Custom Init..........");System.out.println("Custom Init.........."); }}

@PostConstruct@PostConstruct public void init() {public void init() { System.out.println("post construct init1");System.out.println("post construct init1");

}} @PostConstruct@PostConstruct public void init2() {public void init2() { System.out.println("post construct init2");System.out.println("post construct init2");

}} public void setBeanName(String id) {public void setBeanName(String id) { System.out.println("set bean name");System.out.println("set bean name"); this.beanId = id;this.beanId = id; }}

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("set applicationcontext");System.out.println("set applicationcontext"); }}

public void afterPropertiesSet() throws Exception {public void afterPropertiesSet() throws Exception { System.out.println("after properties set...");System.out.println("after properties set..."); }}}}

Life cycle codeLife cycle codepublic class Bean1 implements public class Bean1 implements

BeanNameAware, BeanNameAware, ApplicationContextAware, InitializingBean {ApplicationContextAware, InitializingBean {

private String beanId;private String beanId; public void setBeanName(String id) {public void setBeanName(String id) { System.out.println("set bean name");System.out.println("set bean name"); this.beanId = id;this.beanId = id; }}……}}

Life cycle codeLife cycle codepublic class Bean1 implements public class Bean1 implements

BeanNameAware, BeanNameAware, ApplicationContextAware, InitializingBean {ApplicationContextAware, InitializingBean {

public void public void setApplicationContext( ApplicationContext setApplicationContext( ApplicationContext applicationContext) throws BeansException applicationContext) throws BeansException {{

System.out.println ("set System.out.println ("set applicationcontext");applicationcontext");

}}

}}

Life cycle codeLife cycle codepublic class Bean1 implements public class Bean1 implements

BeanNameAware, BeanNameAware, ApplicationContextAware, InitializingBean ApplicationContextAware, InitializingBean {{

public void afterPropertiesSet() throws public void afterPropertiesSet() throws Exception {Exception {

System.out.println ("after properties System.out.println ("after properties set...");set...");

}}

}}

Life cycle codeLife cycle codepublic class Bean1 implements BeanNameAware, public class Bean1 implements BeanNameAware,

ApplicationContextAware, InitializingBean {ApplicationContextAware, InitializingBean { @PostConstruct@PostConstruct public void init() {public void init() { System.out.println ("post construct init1");System.out.println ("post construct init1");

}} @PostConstruct@PostConstruct public void init2() {public void init2() { System.out.println ("post construct init2");System.out.println ("post construct init2");

}}}} <bean <bean

class="org.springframework.context.annotation.CommonAnnclass="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/> ORotationBeanPostProcessor"/> OR

<context:annotation-config/><context:annotation-config/>

Life cycle codeLife cycle codeFor using <context:annotation-config/>, name space and schema location For using <context:annotation-config/>, name space and schema location

should be specified for context.should be specified for context.<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p" xmlns:p="http://www.springframework.org/schema/p"

xmlns:aop="http://www.springframework.org/schema/aop"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context" xmlns:context="http://www.springframework.org/schema/context"

xmlns:jee="http://www.springframework.org/schema/jee"xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="xsi:schemaLocation="

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/context/spring-context-2.5.xsd

http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsdhttp://www.springframework.org/schema/jee/spring-jee-2.5.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

Prototyping vs. singletonPrototyping vs. singleton• Singleton – A design pattern which Singleton – A design pattern which

ensures that only one instance will be ensures that only one instance will be created for the entire application (per created for the entire application (per JVM), and provides a single point of JVM), and provides a single point of access.access.

• Prototype - When object instantiation is a Prototype - When object instantiation is a lot more expensive than cloning, lot more expensive than cloning, Prototype pattern may offer a useful Prototype pattern may offer a useful optimization technique. (Example: clone optimization technique. (Example: clone in java)in java)

Prototyping vs. singletonPrototyping vs. singleton• <bean id="bean1" class="com.springtraining.lifecycle.Bean1" <bean id="bean1" class="com.springtraining.lifecycle.Bean1"

init-method="customInit" init-method="customInit" singleton= " true " singleton= " true " />/>• <bean id="bean1" class="com.springtraining.lifecycle.Bean1" <bean id="bean1" class="com.springtraining.lifecycle.Bean1"

init-method="customInit" init-method="customInit" scope= " prototype " scope= " prototype " />/>• For using scope attribute, use spring-beans-2.5xsdFor using scope attribute, use spring-beans-2.5xsd<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance” xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation="http://www.springframework.org/schema/xsi:schemaLocation="http://www.springframework.org/schema/beans beans

http://www.springframework.org/schema/beans/spring-beans-http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">2.5.xsd">

Setter injectionSetter injection1. <bean id=“person” class=“Person”>1. <bean id=“person” class=“Person”>

<property name=“firstName” value=“John”/><property name=“firstName” value=“John”/>

</bean></bean>

2. 2. <property name=“firstName"><property name=“firstName">

<value>Johns</value><value>Johns</value>

</property></property>

3. 3. <property name=“department”><property name=“department”>

<ref bean=“department”/><ref bean=“department”/>

</property></property>

<bean id=“department” class=“Department”/><bean id=“department” class=“Department”/>

Inner BeanInner Bean<property name=“department”><property name=“department”>

<ref bean=“department”/><ref bean=“department”/>

</property></property>

<bean id=“department” <bean id=“department” class=“Department”/>class=“Department”/>

Can be written using inner bean as:Can be written using inner bean as:

<property name=“department”><property name=“department”>

<bean class=“Department”/><bean class=“Department”/>

</property></property>

Injecting collectionInjecting collection• List and Array can be set using <list> tag.List and Array can be set using <list> tag.

• Set can be set using <set> tagSet can be set using <set> tag

• Map can be set using <map> tagMap can be set using <map> tag

• Properties can be set using <props> tagProperties can be set using <props> tag

Injecting ListInjecting List<property name="list"><property name="list"> <list><list> <value>listvalu1</value><value>listvalu1</value> <value>listvalu2</value><value>listvalu2</value> <ref bean="childBean"/><ref bean="childBean"/> <list><list> <value>sublist1</value><value>sublist1</value> </list> </list> </list> </list> </property></property>

Injecting SetInjecting Set<property name="set"><property name="set"> <set><set> <value>setvalu1</value><value>setvalu1</value> <value>setvalu2</value><value>setvalu2</value> <ref bean="childBean"/><ref bean="childBean"/> <set><set> <value>subset1</value><value>subset1</value> </set> </set> </set> </set> </property></property>

Injecting MapInjecting Map<property name="map"><property name="map">

<map><map>

<entry key="key1"><entry key="key1">

<value>mapvalue1</value><value>mapvalue1</value>

</entry> </entry>

</map></map>

</property></property>

Injecting PropertiesInjecting Properties<property name="properties"><property name="properties">

<props><props>

<prop <prop key="propkey1">propvalue1</prop>key="propkey1">propvalue1</prop>

</props> </props>

</property></property>

Injecting CollectionsInjecting CollectionsList, Set, Map and Properties values can be List, Set, Map and Properties values can be

(bean |ref | idref| value| null| list| set| map| (bean |ref | idref| value| null| list| set| map| prop)prop)

Constructor InjectionConstructor Injection<bean id=“bean1” class=“Bean1”><bean id=“bean1” class=“Bean1”>

<constructor-arg><constructor-arg>

<value>my bean name<value><value>my bean name<value>

</constructor-arg></constructor-arg>

</bean></bean>

When there is ambiguity in constructor When there is ambiguity in constructor argument, use type or index attribute.argument, use type or index attribute.

Auto WiringAuto Wiring• Dependency is injected automatically Dependency is injected automatically

using auto wiring.using auto wiring.

• <bean id="bean1" <bean id="bean1" class="com.springtraining.autowire.Beanclass="com.springtraining.autowire.Bean1" autowire="byName"/> 1" autowire="byName"/>

<bean id="childBean" <bean id="childBean" class="com.springtraining.autowire.Childclass="com.springtraining.autowire.ChildBean"/>Bean"/>

Auto WiringAuto Wiring• 4 types of auto wiring4 types of auto wiring

• byName, byType, constructor, autodetectbyName, byType, constructor, autodetect

• byType , constructor and autodetect byType , constructor and autodetect throw UnsatisfiedDependencyException throw UnsatisfiedDependencyException on ambiguityon ambiguity

• Autodetect will first try to match by Autodetect will first try to match by constructor and then byType.constructor and then byType.

Special BeansSpecial Beans• Spring treats some beans special, when Spring treats some beans special, when

they implement certain spring specific they implement certain spring specific interfaces.interfaces.

• We can involve in bean’s and bean We can involve in bean’s and bean factory’s life cycle.factory’s life cycle.

• Load configuration information from Load configuration information from property filesproperty files

• Load textual message from property file Load textual message from property file (i18n)(i18n)

• Event handling.Event handling.

Post processing BeansPost processing Beans• Cut into bean’s lifecycle and do some Cut into bean’s lifecycle and do some

process – Post processing.process – Post processing.

• BeanPostProcessor interface has 2 BeanPostProcessor interface has 2 methods.methods.

Object Object postProcessBeforeInitializationpostProcessBeforeInitialization((

Object bean, String name) throws Object bean, String name) throws BeansException;BeansException;

Object Object postProcessAfterInitializationpostProcessAfterInitialization((

Object bean, String name) throws Object bean, String name) throws BeansException;BeansException;

Spring’s built in PostprocessorSpring’s built in Postprocessor• ApplicationContextAwareProcessorApplicationContextAwareProcessor

• DefaultAdvisorAutoProxyCreatorDefaultAdvisorAutoProxyCreator

ApplicationContextAwareProcApplicationContextAwareProcessoressor• ApplicationContextAwareProcessor – set ApplicationContextAwareProcessor – set

application context to beans, which application context to beans, which implements ApplicationContextAware implements ApplicationContextAware interface.interface.

• No need to register. (Custom post No need to register. (Custom post processors should be registered)processors should be registered)

BeanFactoryPostProcessorBeanFactoryPostProcessor• Performs postprocessing on a bean Performs postprocessing on a bean

factory factory after the bean factory has loaded after the bean factory has loaded its bean definitions but its bean definitions but before any of the before any of the beans have been instantiated.beans have been instantiated.

• public void postProcessBeanFactory(public void postProcessBeanFactory(

ConfigurableListableBeanFactory ConfigurableListableBeanFactory beanFactory)beanFactory)

throws BeansException;throws BeansException;

Built in Built in BeanFactoryPostProcessorBeanFactoryPostProcessor• PropertyPlaceholderConfigurer - loads PropertyPlaceholderConfigurer - loads

properties from one or more external properties from one or more external property files and uses those properties property files and uses those properties to fill in placeholder variables in the bean to fill in placeholder variables in the bean wiring XML file.wiring XML file.

• CustomEditorConfigurer - lets you CustomEditorConfigurer - lets you register custom implementations of register custom implementations of java.beans.PropertyEditor to translate java.beans.PropertyEditor to translate property wired values to other property property wired values to other property types.types.

PropertyPlaceholderConfigurePropertyPlaceholderConfigurerr<bean id="bean1" <bean id="bean1"

class="com.springtraining.bpp.propertyphconfigclass="com.springtraining.bpp.propertyphconfig.Bean1">.Bean1">

<property name="name" value="${name}"/><property name="name" value="${name}"/> </bean></bean> <bean id="propertyConfigurer" <bean id="propertyConfigurer"

class="org.springframework.beans.factory.conficlass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">g.PropertyPlaceholderConfigurer">

<property name="location"><property name="location">

<value>com/springtraining/bpp/propertyphconfi<value>com/springtraining/bpp/propertyphconfig/myproperties.properties</value>g/myproperties.properties</value>

</property></property> </bean></bean>

PropertyPlaceholderConfigurePropertyPlaceholderConfigurerr When DriverManagerDataSource is used for data When DriverManagerDataSource is used for data

source, the db specific configuration information can be source, the db specific configuration information can be separated to property file from XML file.separated to property file from XML file.

i18ni18n• ResourceBundleMessageSource uses ResourceBundleMessageSource uses

java.util.ResourceBundle to resolve messages.java.util.ResourceBundle to resolve messages.<bean id="messageSource"<bean id="messageSource"class="org.springframework.context.support.ResourceBunclass="org.springframework.context.support.ResourceBun

dleMessageSource">dleMessageSource"> <property name="basenames"><property name="basenames"> <list> <list>

<value>com/springtraining/i18n/messages</value><value>com/springtraining/i18n/messages</value> </list></list> </property></property> </bean></bean>

applicationContext.getMessage(String,Object[],Locale);applicationContext.getMessage(String,Object[],Locale);

<spring:message code="computer"/><spring:message code="computer"/>

AOP termsAOP terms• Aspect – Cross cutting concern.Aspect – Cross cutting concern.• Advice – Impementation of Aspect.Advice – Impementation of Aspect.• Join Point – Point in the application where Join Point – Point in the application where

aspect can be weaved.aspect can be weaved.• Pointcut – An expression that matches Pointcut – An expression that matches

join point.join point.• Target - The class being advised.Target - The class being advised.• Proxy – The object created after the Proxy – The object created after the

advice applied to the target. (Target + advice applied to the target. (Target + Advice)Advice)

• Advisor – Advice + Poincut. Advisor – Advice + Poincut.

AOP termsAOP terms• Weaving – Process of applying aspect Weaving – Process of applying aspect

to a target. 3 types of weaving.to a target. 3 types of weaving.

1.1. Compile time – need special compiler.Compile time – need special compiler.

2.2. Class Load time – needs special class Class Load time – needs special class loader.loader.

3.3. Runtime – AOP container will Runtime – AOP container will dynamically generate a proxy class that dynamically generate a proxy class that will delegate to the target class.will delegate to the target class.

How spring implements How spring implements AOPAOP• Spring uses Runtime weaving.Spring uses Runtime weaving.

• Advice is written in Java.Advice is written in Java.• Spring uses proxy for weaving.Spring uses proxy for weaving.• If the target bean implements an interface that If the target bean implements an interface that

exposes the required methods, spring exposes the required methods, spring dynamically generate new class implementing dynamically generate new class implementing the interface(s), weave in any advice and the interface(s), weave in any advice and delegate to the target class.delegate to the target class.

• If target doesn’t implement interface, spring If target doesn’t implement interface, spring subclass target, weave advice and delegate subclass target, weave advice and delegate calls to target (super class).calls to target (super class).

Types of AdviceTypes of Advice• Around - MethodInterceptorAround - MethodInterceptor

• Before - BeforeAdviceBefore - BeforeAdvice

• After - AfterReturningAdviceAfter - AfterReturningAdvice

• Throws - ThrowsAdviceThrows - ThrowsAdvice

Defining ProxyFactoryBeanDefining ProxyFactoryBean<bean id="bean1" <bean id="bean1"

class="org.springframework.aop.framework.ProxyFacclass="org.springframework.aop.framework.ProxyFactoryBean">toryBean">

<property name="target" ref="bean1target"/><property name="target" ref="bean1target"/> <property name="interceptorNames"><property name="interceptorNames"> <list><list> <value> myAroundAdvice </value><value> myAroundAdvice </value> <value> myBeforeAdvice </value><value> myBeforeAdvice </value> <value> myAfterReturingAdvice </value><value> myAfterReturingAdvice </value> <value> myAroundAdvice </value><value> myAroundAdvice </value>

</list></list> </property></property> </bean></bean>

Defining AdvicesDefining Advices<bean id="bean1target" <bean id="bean1target"

class="com.springtraining.advice.Bean1"/>class="com.springtraining.advice.Bean1"/> <bean id="myBeforeAdvice" <bean id="myBeforeAdvice"

class="com.springtraining.advice.MyBeforeAdclass="com.springtraining.advice.MyBeforeAdvice"/>vice"/>

<bean id="myAfterReturingAdvice" <bean id="myAfterReturingAdvice" class="com.springtraining.advice.MyAfterRetuclass="com.springtraining.advice.MyAfterReturingAdvice"/>ringAdvice"/>

<bean id="myAroundAdvice" <bean id="myAroundAdvice" class="com.springtraining.advice.MyAroundAclass="com.springtraining.advice.MyAroundAdvice"/>dvice"/>

<bean id="myThrowsAdvice" <bean id="myThrowsAdvice" class="com.springtraining.advice.MyThrowsAclass="com.springtraining.advice.MyThrowsAdvice"/>dvice"/>

MethodBeforeAdviceMethodBeforeAdvicepublic class MyBeforeAdvice implements public class MyBeforeAdvice implements

MethodBeforeAdvice{MethodBeforeAdvice{

public void before(Method arg0, Object[] arg1, Object public void before(Method arg0, Object[] arg1, Object target) throws Throwable {target) throws Throwable {

System.out.println ("IN METHOD BEFORE ADVICE: System.out.println ("IN METHOD BEFORE ADVICE: ");");

System.out.println ("Method:" +arg0);System.out.println ("Method:" +arg0); System.out.println ("Args:" +arg1[0]);System.out.println ("Args:" +arg1[0]);

System.out.println ("Target:" + System.out.println ("Target:" + target.getClass().getName());target.getClass().getName());

}}

}}

AfterReturningAdviceAfterReturningAdvicepublic class MyAfterReturingAdvice implements public class MyAfterReturingAdvice implements

AfterReturningAdvice {AfterReturningAdvice {

public void afterReturning (Object returnValue, Method public void afterReturning (Object returnValue, Method method, Object[] args, Object target) throws method, Object[] args, Object target) throws Throwable {Throwable {

System.out.println("IN AFTER RETURING ADVICE: System.out.println("IN AFTER RETURING ADVICE: ");");

System.out.println ("Method:" + method);System.out.println ("Method:" + method); System.out.println ("Args:" + args[0]);System.out.println ("Args:" + args[0]); System.out.println ("Target:" + System.out.println ("Target:" +

target.getClass().getName());target.getClass().getName()); System.out.println ("Return Value:" + returnValue);System.out.println ("Return Value:" + returnValue);

}}}}

MethodInterceptor MethodInterceptor (Around)(Around)public class MyAroundAdvice implements public class MyAroundAdvice implements

MethodInterceptor {MethodInterceptor {

public Object invoke (MethodInvocation public Object invoke (MethodInvocation methodInvocation) throws Throwable {methodInvocation) throws Throwable {

System.out.println ("BEFORE PROCEED IN System.out.println ("BEFORE PROCEED IN AROUND ADVICE"); System.out.println AROUND ADVICE"); System.out.println ("Method:"+ methodInvocation. ("Method:"+ methodInvocation. getMethod() .getName());getMethod() .getName());

Object returnValue = methodInvocation.proceed();Object returnValue = methodInvocation.proceed(); System.out.println ("AFTER PROCEED IN AROUND System.out.println ("AFTER PROCEED IN AROUND

ADVICE");ADVICE"); return returnValue; }return returnValue; }}}

ThrowsAdviceThrowsAdvicepublic class MyThrowsAdvice implements public class MyThrowsAdvice implements

ThrowsAdvice {ThrowsAdvice {

public void afterThrowing(Method m, Object[] public void afterThrowing(Method m, Object[] args, Object target, Exception e)args, Object target, Exception e)

{{

System.out.println ("Throws Advice: Exception System.out.println ("Throws Advice: Exception " + e + " thrown in method " + m);" + e + " thrown in method " + m);

}}

}}

ProxyFactoryBean ProxyFactoryBean propertiesproperties1.1. Target – target classTarget – target class

2.2. interceptorNames – list of interceptorNames – list of advice/advisoradvice/advisor

3.3. More….More….

Advisor and PointcutAdvisor and Pointcut• Advisor = Advice + PointcutAdvisor = Advice + Pointcut

• Two types of pointcut – static and Two types of pointcut – static and dynamic.dynamic.

• Static pointcut evaluated once when the Static pointcut evaluated once when the proxy is created.proxy is created.

• Dynamic pointcut evaluated dynamically, Dynamic pointcut evaluated dynamically, during invocation.during invocation.

• NameMatchMethodPointcut - staticNameMatchMethodPointcut - static

• RegexpMethodPointcut -staticRegexpMethodPointcut -static

• ControlFlowPointcut - dynamicControlFlowPointcut - dynamic

NameMatchMethodPointcutNameMatchMethodPointcut• Properties – mappedNames (or Properties – mappedNames (or

mappedName), advice.mappedName), advice.

• Matching only applies to the method Matching only applies to the method name itself, not the fully qualified name name itself, not the fully qualified name that includes that class name as well.that includes that class name as well.

• Proxy = Target + Advice/Advisor.Proxy = Target + Advice/Advisor.

NameMatchMethodPointcutNameMatchMethodPointcut• Defining proxy:Defining proxy:

<bean id="bean1" <bean id="bean1" class="org.springframework.aop.framework.Proclass="org.springframework.aop.framework.ProxyFactoryBean">xyFactoryBean">

<property name="target" ref="bean1target"/><property name="target" ref="bean1target"/>

<property name="interceptorNames"><property name="interceptorNames">

<list><list>

<value> myBefore<value> myBeforeAdvisorAdvisor</value></value>

</list></list>

</property></property>

</bean></bean>

NameMatchMethodPointNameMatchMethodPointcutcut• Defining advisor:Defining advisor:

<bean id="myBeforeAdvisor" <bean id="myBeforeAdvisor" class="org.springframework.aop.support.NameMatchMethodPoclass="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">intcutAdvisor">

<property name="mappedNames"><property name="mappedNames"> <list><list> <value>*Service</value><value>*Service</value> </list></list> </property></property> <property name="advice" ref="myBeforeAdvice"/><property name="advice" ref="myBeforeAdvice"/> </bean></bean> <bean id="bean1target" <bean id="bean1target"

class="com.springtraining.namematchadvicor.Bean1"/>class="com.springtraining.namematchadvicor.Bean1"/> <bean id="myBeforeAdvice" <bean id="myBeforeAdvice"

class="com.springtraining.namematchadvicor.MyBeforeAdvice"/>class="com.springtraining.namematchadvicor.MyBeforeAdvice"/>

NameMatchMethodPointNameMatchMethodPointcutcut• Defining advice and target:Defining advice and target:

<bean id="bean1target" <bean id="bean1target" class="com.springtraining.namematchadvclass="com.springtraining.namematchadvicor.Bean1"/>icor.Bean1"/>

<bean id="myBeforeAdvice" <bean id="myBeforeAdvice" class="com.springtraining.namematchadvclass="com.springtraining.namematchadvicor.MyBeforeAdvice"/>icor.MyBeforeAdvice"/>

RegexpMethodPointcutRegexpMethodPointcut• We can use Perl-style regular We can use Perl-style regular

expressions to define the pattern that expressions to define the pattern that should match our intended methods.should match our intended methods.

• Patterns include class name as well as Patterns include class name as well as method name.method name.

RegexpMethodPointcutRegexpMethodPointcut• Defining proxy:Defining proxy:

<bean id="bean1" <bean id="bean1" class="org.springframework.aop.framework.Proclass="org.springframework.aop.framework.ProxyFactoryBean">xyFactoryBean">

<property name="target" ref="bean1target"/><property name="target" ref="bean1target"/>

<property name="interceptorNames"><property name="interceptorNames">

<list><list>

<value> myBefore<value> myBeforeAdvisorAdvisor</value></value>

</list></list>

</property></property>

</bean></bean>

RegexpMethodPointcutRegexpMethodPointcut• Defining Advisor:Defining Advisor:

<bean id="myBeforeAdvisor" <bean id="myBeforeAdvisor" class="org.springframework.aop.support.class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">RegexpMethodPointcutAdvisor">

<property name="pattern"><property name="pattern">

<value>.*Service</value><value>.*Service</value>

</property></property>

<property name="advice" <property name="advice" ref="myBeforeAdvice"/>ref="myBeforeAdvice"/>

</bean></bean>

RegexpMethodPointcutRegexpMethodPointcut• Defining Advice and target:Defining Advice and target:

<bean id="bean1target" <bean id="bean1target" class="com.springtraining.regexpradvisor.class="com.springtraining.regexpradvisor.Bean1"/>Bean1"/>

<bean id="myBeforeAdvice" <bean id="myBeforeAdvice" class="com.springtraining.regexpradvisor.class="com.springtraining.regexpradvisor.MyBeforeAdvice"/>MyBeforeAdvice"/>

AutoproxyingAutoproxying• In ProxyFactoryBean, we can specify only In ProxyFactoryBean, we can specify only

ONE target. ONE target.

• For proxying n number of beans at one For proxying n number of beans at one place, we can use AutoProxying.place, we can use AutoProxying.

• BeanNameAutoProxyCreator - generates BeanNameAutoProxyCreator - generates proxies for beans that match a set of proxies for beans that match a set of names.names.

• DefaultAdvisorAutoProxyCreator can be DefaultAdvisorAutoProxyCreator can be used.used.

BeanNameAutoProxyCreatBeanNameAutoProxyCreatoror<bean id="beanNameAutoProxyCreator" <bean id="beanNameAutoProxyCreator"

class=“org.springframework.aop.framework.autoproxy.class=“org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator ">BeanNameAutoProxyCreator ">

<property name="beanNames"><property name="beanNames"> <list><list> <value>bean*</value><value>bean*</value> </list></list> </property></property> <property name="interceptorNames"><property name="interceptorNames"> <list><list> <value> myBeforeAdvisor</value><value> myBeforeAdvisor</value> </list></list> </property></property> </bean></bean>

BeanNameAutoProxyCreatBeanNameAutoProxyCreatoror <bean id="myBeforeAdvisor" <bean id="myBeforeAdvisor"

class="org.springframework.aop.support.class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">RegexpMethodPointcutAdvisor">

<property name="pattern"><property name="pattern">

<value>.*Service</value><value>.*Service</value>

</property></property>

<property name="advice" <property name="advice" ref="myBeforeAdvice"/>ref="myBeforeAdvice"/>

</bean></bean>

BeanNameAutoProxyCreatBeanNameAutoProxyCreatoror<bean id="bean1" <bean id="bean1"

class="com.springtraining.beannameautoclass="com.springtraining.beannameautoproxy.Bean1"/>proxy.Bean1"/>

<bean id="bean2" <bean id="bean2" class="com.springtraining.beannameautoclass="com.springtraining.beannameautoproxy.Bean2"/>proxy.Bean2"/>

<bean id="myBeforeAdvice" <bean id="myBeforeAdvice" class="com.springtraining.beannameautoclass="com.springtraining.beannameautoproxy.MyBeforeAdvice"/>proxy.MyBeforeAdvice"/>

DefaultAdvisorAutoProxyCrDefaultAdvisorAutoProxyCreatoreator• Without specifying the bean names to be Without specifying the bean names to be

proxied, container will find matching proxied, container will find matching beans from the pointcut expression(s) in beans from the pointcut expression(s) in advisor, and apply advices.advisor, and apply advices.

DefaultAdvisorAutoProxyCrDefaultAdvisorAutoProxyCreatoreator<bean id="autoProxyCreator"<bean id="autoProxyCreator"

class="org.springframework.aop.frameworkclass="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreat.autoproxy.DefaultAdvisorAutoProxyCreator"/>or"/>

DefaultAdvisorAutoProxyCrDefaultAdvisorAutoProxyCreatoreator<bean id="myBeforeAdvisor" <bean id="myBeforeAdvisor"

class="org.springframework.aop.support.class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">RegexpMethodPointcutAdvisor">

<property name="pattern"><property name="pattern">

<value>.*Service</value><value>.*Service</value>

</property></property>

<property name="advice" <property name="advice" ref="myBeforeAdvice"/>ref="myBeforeAdvice"/>

</bean></bean>

SPRING ORM SUPPORTSPRING ORM SUPPORT

HibernateHibernate• ORM – Object Relational MappingORM – Object Relational Mapping

• Inspired by the success of Hibernate, the EJB 3 Expert Group used several key concepts and APIs from Hibernate in its redesign of entity beans.

• When you work with an SQL database in a Java application, the Java code issues SQL statements to the database via the Java DataBase Connectivity (JDBC) API.

HibernateHibernate• Business Entities – Represented as Business Entities – Represented as

domain objects, object oriented domain objects, object oriented representationrepresentation. Represented as tables in relational data base management systems.

• Direct SQL can be fine-tuned in every aspect, but the drawbacks, such as lack of portability and maintainability, are significant, especially in the long run.

ORMORM• object/relational mapping is the

automated (and transparent) persistence of objects in a Java application to the tables in a relational database, using metadata that describes the mapping between the objects and the database. ORM, in essence, works by (reversibly) transforming data from one representation to another.

Getting DatasourceGetting Datasource• BasicDataSource – Jakarta Commons

DBCP Project

• JndiObjectFactoryBean – A jndi factory implementation fom spring for getting data source from server.

• DriverManagerDataSource – Lightweight datasouce implementation from spring.

top related