Your SlideShare is downloading. ×
Spring Basics
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Spring Basics

817

Published on

Spring Basics

Spring Basics

Published in: Technology, Education
1 Comment
3 Likes
Statistics
Notes
No Downloads
Views
Total Views
817
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
83
Comments
1
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Cruising on to Enterprise Development
  • 2. The Spring Framework Lightweight: Spring is lightweight in terms of both size (justover 2..5 MB) and processing overhead. Dependency Injection: Spring promotes loose couplingthrough dependency injection (DI). When DI is applied, objectsare passively given their dependencies instead of creating orlooking for dependent objects for themselves. Aspect-oriented: Spring comes with rich support for aspect-oriented programming (AOP) that enables cohesivedevelopment by separating application business logic fromsystem services. Container: Spring is a container as it contains and manages thelifecycle and configuration of application objects. One candeclare how each of your application objects should becreated, how they should be configured, and how they should beassociated with each other using Spring. Framework: Spring allows to configure and compose complexapplications from simpler components and provides muchinfrastructure functionality. In Spring, the application objects arecomposed declaratively, typically in an XML file.
  • 3. The Spring ModulesAOPORMDAOJMX JMSJCAWebContextMVCPortletMVCRemotingCore
  • 4. Spring Modules: Core and Context Core Container: It provides the fundamental functionalityof the Spring Framework and contains theBeanFactory, which is the fundamental Spring container. Application context module: Spring’s application contextbuilds on the core container . It extends the concept of BeanFactory, adding support forinternationalization (I18N) messages, application lifecycleevents, and validation. In addition, it supplies many enterprise services such asemail, JNDI access, EJB integration, remoting, andscheduling and support for integration with templatingframeworks such as Velocity and FreeMarker.
  • 5. Spring Modules: AOP and DAO Spring’s AOP module: It provides support for aspect-orientedprogramming and basis for developing aspects in a Spring enabledapplication. Like DI, AOP supports loose coupling of applicationobjects. Spring’s AOP module offers several approaches to buildingaspects, including building aspects based on AOP Alliance interfacesand support for AspectJ. JDBC abstraction and the DAO module: Spring’s JDBC and DataAccess Objects (DAO) module abstracts away the boilerplate code suchas getting a connection, creating a statement, processing a resultset tokeep the database code clean and simple, and prevents problemsresulting from failure to close database resources. It also builds a layer of meaningful exceptions on top of the errormessages given by several database servers. This module uses Spring’s AOP module to provide transactionmanagement services for objects in a Spring application.
  • 6. Spring Modules: ORM Object-relational mapping (ORM) integrationmodule: It provides ORM support over straight JDBC. Spring’s ORM support builds on the DAOsupport, providing a convenient way to build DAOs forseveral ORM solutions. Spring doesn’t attempt to implement its own ORMsolution, but does provide hooks into several popular ORMframeworks, including Hibernate, Java PersistenceAPI, Java Data Objects, and iBATIS SQL Maps. Spring’s transaction management supports each of theseORM frameworks as well as JDBC.
  • 7. Spring Modules: JMX, JCA, MVC Java Management Extensions (JMX): Spring’s JMX module makes iteasy to expose the application’s beans as JMX Mbeans and makes itpossible to monitor and reconfigure a running application. Java EE Connector API (JCA) The Java EE Connection API (JCA) provides a standard way ofintegrating Java applications with a variety of enterprise informationsystems, including mainframes and databases. JCA is much like JDBC, except where JDBC is focused on databaseaccess, JCA is a more general-purpose API connecting to legacysystems. Spring’s support for JCA is similar to its JDBC support, abstracting awayJCA’s boilerplate code into templates. The Spring MVC framework Java has number of MVC frameworks, with Apache Struts, JSF,WebWork, and Tapestry among the most popular MVC choices. Spring integrates with several popular MVC frameworks and also hasits own capable MVC framework that promotes Spring’s looselycoupled techniques in the web layer of an application.
  • 8. Spring Modules: Portlet MVC, Web Spring Portlet MVC: The portlet-based applicationsaggregate several bits of functionality on a single web page.It provides a view into several applications at once. SpringPortlet MVC builds on Spring MVC to provide a set ofcontrollers that support Java’s portlet API. Spring’s web module: Spring MVC and Spring PortletMVC require special consideration when loading theSpring application context. Therefore, Spring’s web moduleprovides special support classes for Spring MVC and SpringPortlet MVC. The web module also supports several web-oriented tasks,such as multipart file uploads and programmatic bindingof request parameters to your business objects. It also contains integration support with Apache Struts andJavaServer Faces.
  • 9. Spring Modules: Remoting, JMS Remoting Spring’s remoting support enables the application to expose thefunctionality of the Java objects as remote objects. The remoting module also makes simple work of wiring remoteobjects into the application as if they were local POJOs. Several remoting options are available, including RemoteMethod Invocation (RMI), Hessian, Burlap, JAX-RPC, andSpring’s own HTTP Invoker. Java Message Service (JMS) Message-oriented communication, is reliable and guaranteesdelivery of messages, even if the network and endpoints areunreliable. Spring’s Java Message Service (JMS) module helps to sendmessages to JMS message queues and topics. At the same time, this module also helps you create message-driven POJOs that are capable of consuming asynchronousmessages.
  • 10. Starting Spring <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="greetingService” class="com.spring.GreetingServiceImpl"> <property name="greeting" value="Buenos Dias!" /> </bean> </beans> At the root of the simple XML file is the <beans> element, which is theroot element of any Spring configuration file. The <bean> element is used to tell the Spring container about a classand how it should be configured. The id attribute is used to name the bean greetingService and the classattribute specifies the bean’s fully qualified class name. Within the <bean> element, the <property> element is used to set aproperty, in this case is the greeting property.
  • 11. Starting Spring The Spring can set the property through a single argumentconstructor. For example: <bean id="greetingService" class="com.spring.chapter.hello.GreetingServiceImp"> <constructor-arg value="Buenos Dias!" /> </bean> A BeanFactory loads the bean definitions and wires the beanstogether. The reference is obtained using getBean() method of BeanFactoryas shown in following code: BeanFactory factory = new XmlBeanFactory(newFileSystemResource("hello.xml")); GreetingService greetingService =(GreetingService)factory.getBean("greetingService");
  • 12. Dependency Injection Objects are given their dependencies at creation timeby some external entity that coordinates each object inthe system. The key benefit of DI is loose coupling. Loose Coupling: If an object only knows about itsdependencies by their interface (not theirimplementation or how they were instantiated) thenthe dependency can be swapped out with a differentimplementation without the depending objectknowing the difference.
  • 13. Aspect Oriented Programming It is a programming technique that promotes separation ofconcerns within a software system. Some Systems have software components that carryadditional responsibility beyond their core functionality. System services such as logging, transactionmanagement, and security often find their way intocomponents whose core responsibility is something else. The code that implements the systemwide services isduplicated across multiple components and thecomponents are littered with code that isn’t aligned withtheir core functionality.
  • 14. Aspect Oriented Programming AOP makes it possible to modularize systemwideservices and then apply them declaratively to thecomponents that they should affect. With AOP, one can cover the core application withlayers of functionality. The layers can be applied declaratively throughout theapplication in a flexible manner without allowing thecore application to know their existence. This is a powerful concept, as it keeps the security,transaction, and logging concerns from littering theapplication’s core business logic.
  • 15. Weaving the Aspect <bean id="minstrel“ class="com. knight.Minstrel"/> <aop:config> <aop:aspect ref="minstrel"> <aop:pointcut id="questPointcut" expression="executing embarkOnQuest() " /> <aop:before method="singBefore“ pointcut-ref="questPointcut“ arg-names="bean" /> <aop:after-returning method="singAfter“ pointcut-ref="questPointcut“ arg-names="bean" /> </aop:aspect> </aop:config>
  • 16. Description of Aspect ■ First, find a <bean> declaration, or creates a bean in Spring. If thebean doesn’t have any dependencies, then there’s no need to inject itwith anything. ■ Next, set up the <aop:config> element which contains most ofSpring’s AOP configuration elements. ■ Within <aop:config> we have an <aop:aspect> element whichindicates declaration of an aspect. The functionality of the aspect is defined in the bean that is referred toby the ref attribute. An aspect is made up of pointcuts (places where the aspectfunctionality will be applied) and advice (how to apply thefunctionality). ■ The <aop:pointcut> element defines a pointcut that is triggered bythe execution of a method. ■ Finally, There are two bits of AOP advice. The <aop:before> elementdeclares a method to be called before the pointcut, while the<aop:after> element declares the method to be called after thepointcut. The pointcut in both cases is a reference to id of<aop:pointcut>, which is the execution of embarkOnQuest().
  • 17. Spring Container The spring container is at the core of the Spring Framework. Spring’s container uses dependency injection (DI) tomanage the components that make up an application. Spring comes with several container implementations thatcan be categorized into two distinct types. Bean factories (defined by theorg.springframework.beans.factory.BeanFactory interface)are the simplest of containers, providing basic support forDI. Application contexts (defined by theorg.springframework.context.ApplicationContext interface)build on the notion of a bean factory by providingapplication framework services, such as the ability toresolve textual messages from a properties file and theability to publish application events to interested eventlisteners.
  • 18. The BeanFactory A bean factory is an implementation of the Factory designpattern and is responsible for creating and dispensingmany types of beans. It is able to create associations between collaboratingobjects as they are instantiated and delivers fullyconfigured objects. It also takes part in the lifecycle of a bean, making calls tocustom initialization and destruction methods, if thosemethods are defined. Most common implementation is XmlBeanFactory, whichloads its beans based on the definitions contained in anXML file.
  • 19. XMLBeanFactory XmlBeanFactory requires to pass an instance oforg.springframework.core.io.Resource to the constructor. The Resource object provides the XML to the factory. FileSystemResource is commonly used to create anXmlBeanFactory whose bean definitions are read from anXML file in the file system: BeanFactory factory = new XmlBeanFactory(newFileSystemResource("c:/beans.xml")); To retrieve a bean from a BeanFactory, simply call thegetBean() method, passing the ID of the bean to retrieve: MyBean myBean = (MyBean)factory.getBean("myBean"); When getBean() is called, the factory will instantiate thebean and set the bean’s properties using DI thus beginningthe life of a bean within the Spring container.
  • 20. Resource ImplementationsResource Implementn PurposeByteArrayResource Defines a resource whose content is given by an array ofbytesClassPathResource Defines a resource that is to be retrieved from theclasspathDescriptiveResource Defines a resource that holds a resource description butno actual readable resourceFileSystemResource Defines a resource that is to be retrieved from the filesystemInputStreamResource Defines a resource that is to be retrieved from an inputstreamPortletContextResource Defines a resource that is available in a portlet contextServletContextResource Defines a resource that is available in a servlet contextUrlResource Defines a resource that is to be retrieved from a givenURL
  • 21. Application Context ApplicationContext is similar to BeanFactory asApplicationContext interface extends the BeanFactory interface. It loads bean definitions, wire beans together, and dispensebeans upon request. Application contexts provide a means for resolving textmessages, including support for internationalization (I18N) ofthe messages. Application contexts provide a generic way to load fileresources, such as images. Application contexts can publish events to beans that areregistered as listeners. An Application Context preloads all singleton beans uponcontext startup compared to the bean factory which loads allbeans but defers bean creation until the getBean() method iscalled.
  • 22. Implementations of ApplicationContext ClassPathXmlApplicationContext: Loads a contextdefinition from an XML file located in the classpath,treating context definition files as classpath resources. FileSystemXmlApplicationContext: Loads a contextdefinition from an XML file in the file system. XmlWebApplicationContext: Loads contextdefinitions from an XML file contained within a webapplication. FileSystemXmlApplicationContext looks for the xmlfile in a specific location within the file system,whereas ClassPathXmlApplicationContext looks forxml file anywhere in the classpath (including JARfiles).
  • 23. Lifecycle of a Bean in Spring Container
  • 24. Steps in Life of a BeanStep Description1. Instantiate Spring instantiates the bean.2. Populate properties Spring injects the bean’s properties.3. Set bean name. If the bean implements BeanNameAware, Spring passesthe bean’s ID to setBeanName().4. Set bean factory. If the bean implements BeanFactoryAware, Springpasses the bean factory to setBeanFactory().5. Postprocess(before init).If there are any BeanPostProcessors, Spring calls theirpostProcessBeforeInitialization() method.6. Initialize beans. If the bean implements InitializingBean, itsafterPropertiesSet() method will be called.7. Postprocess(after init).If there are any BeanPostProcessors, Spring calls theirpostProcessAfterInitialization() method.8. Bean is ready to use. Bean is ready to be used by the application and willremain in the bean factory until it is no longer needed.9. Destroy bean. If the bean implements DisposableBean, its destroy()method will be called.
  • 25. Lifecycle of a Bean in Spring application context
  • 26. Declaring a Simple Bean <bean id="duke" class="com.spring.springidol.Juggler" /> The <bean> element is the most basic configuration unit inSpring. It tells Spring to create an object for us. The id attribute gives the bean a name by which it will bereferred to in the Spring container. The class attribute tells Spring what type the bean will be. When the Spring container loads its beans, it willinstantiate the bean defined using the default constructor. ApplicationContext ctx = newClassPathXmlApplicationContext("spring-idol.xml"); Performer performer = (Performer) ctx.getBean("duke");
  • 27. Injecting through constructors <bean id="duke“ class="com.spring.springidol.Juggler"> <constructor-arg value="15" /> <constructor-arg ref="sonnet29" /> </bean> The <constructor-arg> element is used to give Springadditional information to use when constructing a bean When a <constructor-arg> with a value attribute set, aconstructor taking the arguments other than the defaultconstructor is called. The ref attribute is used to indicate that the value passed tothe constructor should be a reference to the bean. Constructor injection is a surefire way to guarantee that abean is fully configured before it is used.
  • 28. Injecting into bean properties A JavaBean’s properties are private and will have a pairof accessor methods in form of setXXX() and getXXX(). Bean properties can be configured using the<property> element which injects the property bycalling a property’s setter method. The value attribute of the <property> can beStrings, numeric values as well as boolean values. Similar to constructors, the ref attribute is used toindicate that the value passed to the setter methodshould be a reference to the bean.
  • 29. Injecting inner beans Inner beans are beans that are defined within the scope ofanother bean. <bean id="kenny” class="com.spring.Instrumentalist"> <property name="song" value="Jingle Bells" /> <property name="instrument"> <bean class="org.springinaction.springidol.Saxophone" /> </property> </bean> An inner bean is defined by declaring a <bean> element directlyas a child of the <property> element to which it will be injected. Inner beans can be used to wire setter injection but also theconstructor arguments. The inner beans do not have an id attribute set as one neverneeds to refer to the inner bean by name. Inner beans are only useful for injection once and can’t bereferred to by other beans.
  • 30. Wiring Collections Spring has four types of collection configuration elements. The <list> and <set> elements are useful when configuringproperties that are either arrays or some implementation ofjava.util.Collection. The <map> and <props> are the two elements corresponding tocollections java.util.Map and java.util.Properties.CollectionElementUseful for<list> Wiring a list of values, allowing duplicates.<set> Wiring a set of values, ensuring no duplicates<map> Wiring a collection of name-value pairs where name andvalue can be of any type<props> Wiring a collection of name-value pairs where the nameand value are both Strings
  • 31. Lists, Arrays and Sets The <list> element contains one or more values. The <ref> elements are used to define the values as references toother beans in the Spring context. It is also possible to use other value-setting Spring elements asthe members of a <list>, including <value>, <bean>, and <null/> A <list> may also contain another <list> as a member formultidimensional lists. <list> may be used with properties that are of anyimplementation of java.util.Collection or an array. <bean id="hank" class="com.spring.springidol.OneManBand"> <property name="instruments"> <list> <ref bean="guitar" /> <ref bean="cymbal" /> </list> </property> </bean> <set> ensures that each of its members is unique.
  • 32. Maps The <map> element declares a value of type java.util.Map. Each <entry> element defines a member of the Map. The key attribute specifies the key of the entry as a String whilethe key-ref attribute specifies the key of the entry as a referenceto another bean within the Spring context. Similarly, the value attribute specifies the value of the entry as aString while the value-ref attribute defines the value of the entryas a reference to another bean within the Spring context. <bean id="hank" class="com.spring.OneManBand"> <property name="instruments"> <map> <entry key="GUITAR" value-ref="guitar" /> <entry key="CYMBAL" value-ref="cymbal" /> </map> </property> </bean>
  • 33. Properties Properties can be used instead of configuring a Map whoseentries have both String keys and String values. The Properties class limits the keys and values to Strings. The <props> element constructs a java.util.Properties valuewhere each member is defined by a <prop> element. Each <prop> element has a key attribute that defines the key ofeach Properties member, while the value is defined by thecontents of the <prop> element. ■ <props> is the element used to define a collection value of type java.util.Properties. ■ <prop> is the element used to define a member value of a<props> collection. <property name="instruments"> <props> <prop key="GUITAR">STRUM STRUM</prop> </props> </property>
  • 34. Writing nulls To set a property to null, you simply use the <null/>element. For example: <property name="someNonNullProperty"> <null/> </property> Another reason for explicitly wiring null into aproperty is to override an autowired property value.
  • 35. Autowiring Spring automatically wires beans together by setting the autowireproperty on each <bean> in order for Spring to autowire. Spring provides four types of autowiring ■ byName—Attempts to find a bean in the container whose name (orID) is the same as the name of the property being wired. If a matchingbean is not found, the property will remain unwired. ■ byType—Attempts to find a single bean in the container whose typematches the type of the property being wired. If no matching bean isfound, the property will not be wired. If more than one bean matches, anorg.springframework.beans.factory.UnsatisfiedDependencyExceptionwill be thrown. ■ constructor—Tries to match up one or more beans in the containerwith the parameters of one of the constructors of the bean being wired.In the event of ambiguous beans or ambiguous constructors, anorg.springframework. beans.factory.UnsatisfiedDependencyExceptionwill be thrown. ■ autodetect—Attempts to autowire by constructor first and then usingbyType. Ambiguity is handled the same way as with constructor andbyType wiring.
  • 36. Autowiring By default, beans will not be autowired unless you set theautowire attribute. A default autowiring can be set for all beans within theSpring context by setting default-autowire on the root<beans> element. <beans default-autowire="byName"> Even after autowiring a bean, it can still use the <property>element on any property as if autowire is not set. In constructor autowiring, one cannot mix<constructorarg> elements with constructor autowiring. Autowiring lacks clarity as the Spring configuration XMLdoes not have the explicit details of wiring of the beans.
  • 37. Bean Scoping By default, all Spring beans are singletons. To force Spring to produce a new bean instance each timeits needed, the bean’s scope attribute is set to prototype. Spring Bean Scopes are as follows:Scope Descriptionsingleton Scopes the bean definition to a single instance per Spring container(default).prototype Allows a bean to be instantiated any number of times (once per use).request Scopes a bean definition to an HTTP request. Only valid when usedwith a webcapable Spring context (such as with Spring MVC).session Scopes a bean definition to an HTTP session. Only valid when usedwith a webcapable Spring context (such as with Spring MVC).global-sessionScopes a bean definition to a global HTTP session. Only valid whenused in a portlet context.
  • 38. Creating Beans from Factory Methods The <bean> element has a factory-method attribute to specify a staticmethod to be invoked instead of the constructor to create an instance ofa class. Initialization on demand technique to configure singleton as bean inspring: public class Stage {private Stage() {}private static class SingletonHolder {static Stage instance = new Stage();}public static Stage getInstance() {return SingletonHolder.instance; }} To configure a bean in the Spring context, we simply use factory-method as follows: <bean id=“iStage“ class="co.Stage“ factory-method="getInstance" /> Factory methods can be used to wire an object produced by a staticmethod.
  • 39. Initializing and destroying beans The init-method attribute specifies a method that is tobe called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that iscalled just before bean is removed from the container. <bean id="kenny"class="com.spring.Instrument" init-method="tuneInstrument" destroy-method="cleanInstrument"> </bean>
  • 40. Defaulting methods and Bean Interfaces If many of the beans in a context definition file will haveinitialization or destroy methods with the same name, thenthe default-init-method and default-destroy-methodattributes are used on the <beans> element. The default-init-method / default-destroy-methodattribute sets an initialization / destroy methodrespectively across all beans in a given context definition. The class could also implement the two special Springinterfaces: InitializingBean and DisposableBean, whichallows the bean to hook into the bean lifecycle. The InitializingBean interface mandates that the classimplements afterPropertiesSet() and is called once allspecified properties for the bean have been set. Similarly, DisposableBean requires that a destroy()method be implemented. and is called when the bean isdisposed of by the container.
  • 41. Aspect Oriented Programming (AOP) In software development, functions that span multiplepoints of an application are called cross-cuttingconcerns. Aspect-oriented programming helps to separatecross-cutting concerns from business logic. Cross-cutting concerns are modularized into specialobjects called aspects. Aspects are often described in terms ofadvice, pointcuts, and joinpoints.
  • 42. AOP Terminology Advice: It is the job of an aspect. Advice defines both the what and the when of an aspect. Advice describes the job performed by aspect andaddresses the question of when to perform the job. Jointpoints: A joinpoint is a point in the execution of theapplication where an aspect can be plugged in. Such point could be a method being called, an exceptionbeing thrown, or even a field being modified. These are the points where the aspect’s code can beinserted into the normal flow of the application to add newbehavior.
  • 43. AOP Terminology Pointcut: Pointcuts help narrow down the joinpointsadvised by an aspect. If advice defines the what and when of aspects thenpointcuts define the where. A pointcut definition matches one or more joinpoints atwhich advice should be woven. Often you specify the pointcuts using explicit class andmethod names or through regular expressions that definematching class and method name patterns. Aspect: An aspect is the merger of advice and pointcuts. Advice and Pointcuts define everything there is to knowabout an aspect—what it does and where and when it doesit.
  • 44. AOP Terminology Introduction: It allows to add new methods or attributesto existing classes giving them new behavior and state. Target: It is the object that is being advised. This can beeither an object written or a third-party object added forcustom behavior. Without AOP, the object would have to contain its primarylogic plus the logic for any cross-cutting concerns. With AOP, the target object is free to focus on its primaryconcern, oblivious to any advice being applied. Proxy: It is the object created after applying advice to thetarget object. As far as the client objects are concerned, thetarget object (pre-AOP) and the proxy object (post-AOP)are the same—as they should be.
  • 45. AOP Terminology Weaving: It is the process of applying aspects to a targetobject to create a new, proxied object. The aspects are woven into the target object at the specifiedjoinpoints. The weaving can take place at several points in the targetobject’s lifetime: ■ Compile time—Aspects are woven in when the targetclass is compiled. ■ Classload time—Aspects are woven in when the targetclass is loaded into the JVM. ■ Runtime—Aspects are woven in sometime during theexecution of the application. Typically, an AOP containerwill dynamically generate a proxy object that will delegateto the target object while weaving in the aspects. Same asSpring AOP.
  • 46. Spring AOP The ability to create pointcuts that define the joinpoints atwhich aspects should be woven makes it an AOP framework. Spring’s support for AOP comes in four flavors: ■ Classic Spring proxy-based AOP (available in all versionsof Spring) ■ @AspectJ annotation-driven aspects (only available inSpring 2.0) ■ Pure-POJO aspects (only available in Spring 2.0) ■ Injected AspectJ aspects (available in all versions ofSpring) The first three items are all variations on Spring’s proxy-based AOP.
  • 47. Spring Advises Objects at Runtime In Spring, aspects are woven into Spring-managedbeans at runtime by wrapping them with a proxy class. The proxy class poses as the target bean, interceptingadvised method calls and forwarding those calls to thetarget bean. Between the time that the proxy intercepts the methodcall and the time it invokes the target bean’smethod, the proxy performs the aspect logic. In case of an ApplicationContext, the proxied objectswill be created when it loads all of the beans from theBeanFactory.
  • 48. Spring Advises Objects at Runtime Spring generates proxied classes in two ways. If the target object implements an interface(s) that exposesthe required methods, Spring uses thejava.lang.reflect.Proxy class which allows to dynamicallygenerate a new class that implements the necessaryinterfaces, weave in any advice, and proxy any calls to theinterfaces to the target class. If your target class does not implement an interface, Springuses the CGLIB library to generate a subclass to your targetclass. When creating this subclass, Spring weaves in advice anddelegates calls to the subclass to the target class. ■ Creating a proxy with interfaces is favored over proxyingclasses, since this leads to a more loosely coupledapplication. ■ Methods marked as final cannot be advised. Spring only supports method joinpoints.
  • 49. Creating classic Spring Aspects All of the interfaces are part of the SpringFramework, except for MethodInterceptor. The five types of advice, defined by an interface are asfollows:Advice type InterfaceBefore org.springframework.aop.MethodBeforeAdviceAfter-returning org.springframework.aop.AfterReturningAdviceAfter-throwing org.springframework.aop.ThrowsAdviceAround org.aopalliance.intercept.MethodInterceptorIntroduction org.springframework.aop.IntroductionInterceptor
  • 50. Before Advice and After Advice MethodBeforeAdvice interface requires a before() method to beimplemented: public void before(Method method, Object[] args, Object target) { } The before() method takes three parameters. The first parameter is a java.lang.reflect.Method object that representsthe method to which the advice is being applied. The second parameter is an array of Objects that are the arguments thatwere passed to the method when the method was called. The final parameter is the target of the method invocation (i.e., theobject on which the method was called). AfterReturningAdvice requires that an afterReturning() method to beimplemented: public void afterReturning(Object returnValue, Method method,Object[] args, Object target) { } The only difference from the before method is that an additionalparameter has been added as the first parameter which holds the valuethat was returned from the invoked method. AfterReturningAdvice only allows you to inspect the returned value, notto change it.
  • 51. After throwing advice ThrowsAdvice interface doesn’t require that anymethod be implemented. ThrowsAdvice is only a marker interface that tellsSpring that the advice may wish to handle a thrownexception. An implementation of ThrowsAdvice may implementone or more afterThrowing() methods whosesignatures take the following form: public void afterThrowing([method], [args], [target],throwable);
  • 52. Around advice Around advice is effectively before, after-returning, andafter-throwing advice all rolled into one. In Spring, around advice is defined by the AOP Alliance’sMethodInterceptor interface. The MethodInterceptor interface requires that only aninvoke() method be implemented. It calls proceed() on the method invocation to cause theadvised method to be invoked. Around advice makes it possible to write advice thatperforms some postprocessing on a method’s return valuebefore returning the value to the caller.
  • 53. Defining pointcuts and advisors The joinpoints are the points within application codewhere aspect advice could be woven in. Pointcuts are a way of selecting a subset of all possiblejoinpoints where advice should be woven. Two of the most useful pointcuts are regularexpression pointcuts and AspectJ expression pointcuts.
  • 54. Regular Expression Pointcut Pointcut selects the method(s) that advice will be appliedto, usually by matching a method signature against somepattern. Spring comes with two classes that implement regularexpression pointcuts: ■org.springframework.aop.support.Perl5RegexpMethodPointcut—Useful when an application will be running in apre-Java 1.4 environment. Requires Jakarta ORO. ■org.springframework.aop.support.JdkRegexpMethodPointcut—Best choice when running in Java 1.4 or higher.Does not require Jakarta ORO. Jakarta ORO: A set of text-processing Java classes thatprovide Perl5 compatible regular expressions.
  • 55. Declaring regular expression pointcut <bean id="performPointcut“class="org.springframework.aop.support.JdkRegexpMethodPointcut"> <property name="pattern" value=".*perform" /> </bean> The pattern property is used to specify the pointcut pattern used inmethod matching. The pattern property has been set to a regular expression thatshould match any method in any class. The regular expression pointcut is associated with an advice usingthe <bean> element. DefaultPointcutAdvisor is an advisor class that simply associatesadvice with a pointcut. <bean id="audienceAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="advice" ref="audienceAdvice" /> <property name="pointcut" ref="performancePointcut" /> </bean>
  • 56. Combining a pointcut with advisor RegexpMethodPointcutAdvisor is a special advisorclass that lets you define both a pointcut and anadvisor in a single bean. The <bean> declaration is as follows: <bean id="audienceAdvisor" class="org.springframework.aop.support. ➥ RegexpMethodPointcutAdvisor"> <property name="advice" ref="audienceAdvice" /> <property name="pattern" value=".*perform" /> </bean>
  • 57. Defining AspectJ pointcuts AspectJ’s pointcut language is a true pointcut expression language. AspectJ-style expressions can be used to defining the Springpointcuts, using AspectJExpressionPointcut. The following <bean> declares the performance pointcut using anAspectJ pointcut expression: <bean id="performancePointcut" class="org.springframework.aop.aspectj. ➥ AspectJExpressionPointcut"> <property name="expression" value="execution(*Performer+.perform(..))" /> </bean> The pointcut expression is defined as a value of the expressionproperty.
  • 58. Defining AspectJ pointcuts The AspectJ expression pointcut can be associated with the advice usingthe DefaultPointcutAdvisor, similar to the regular expressionpointcut. Also, a special advisor allows to define the pointcut expression as aproperty of the advisor simplifying how pointcuts and advice are tiedtogether. For AspectJ pointcut expressions, the advisor class to use isAspectJExpressionPointcutAdvisor. The following <bean> applies the advice to a method using an AspectJpointcut expression: <bean id="audienceAdvisor" class="org.springframework.aop.aspectj. ➥ AspectJExpressionPointcutAdvisor"> <property name="advice" ref="audienceAdvice" /> <property name="expression" value="execution(* *.perform(..))" /> </bean>
  • 59. AspectJ-style pointcuts Spring AOP uses Aspect-style pointcuts to select places to applyadvice. Following is the pointcut which specifies the advice that shouldbe applied on any method named “perform” on any class withany number of arguments.
  • 60. ProxyFactoryBean A proxied bean allows to be advised by an advisor. Spring’s ProxyFactoryBean is a factory bean that produces a proxythat applies one or more interceptors (and advisors) to a bean. The following <bean> definition creates a proxy for the duke bean: <bean id="duke”class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="dukeTarget" /> <property name="interceptorNames"value="audienceAdvisor" /> <property name="proxyInterfaces“ value="com.Performer" /> </bean> The proxy will use the pointcut to decide whether advice should beapplied (or not), and then it invokes the advised bean itself.
  • 61. ProxyFactoryBean The target property tells ProxyFactoryBean which bean it willbe proxying. The interceptorNames property tells ProxyFactoryBean whichadvisors to apply to the proxied bean. The interceptorNames property takes an array of Strings, ofwhich each member is the name of an interceptor/advisor beanin the Spring context. An array is represented by XML as follows: <property name="interceptorNames"> <list> <value>audienceAdvisor</value> </list> </property> The final property set on ProxyFactoryBean is proxyInterfaceswhich tells ProxyFactoryBean which interface(s) the proxyshould implement. ProxyFactoryBean produces a Java dynamic proxy that advisesthe target bean and the proxyInterfaces provides a way to invokemethods on that proxy. The proxyInterfaces property is actually, an array ofjava.lang.Class.
  • 62. Abstracting ProxyFactoryBean When the proxyInterfaces property and the interceptorNames property are thesame for all the beans, but only the target property is different then an abstractProxyFactoryBean is used. When a single ProxyFactoryBean is declared as an abstract bean, then thatdeclaration is reused as a parent for each of the advised beans. <bean id="audienceProxyBase" class="org.springframework.aop.framework.ProxyFactoryBean“ abstract="true"> <property name="proxyInterfaces“ value="com.spring.Performer" /> <property name="interceptorNames" value="audienceAdvisor" /> </bean> The abstract attribute set to true indicates that it is an abstract bean and thatSpring shouldn’t try to instantiate it directly. Instead, the bean will serve as the basis for the other performer beans. <bean id="stevie" parent="audienceProxyBase"> <property name="target" ref="stevieTarget" /> </bean> Only variant target property is declared while common properties are inheritedfrom the parent bean.
  • 63. Autoproxying Spring provides support for automatic proxying of beans. Autoproxying provides a more complete AOPimplementation by letting an aspect’s pointcut definitiondecide which beans need to be proxied, rather thanexplicitly create proxies for specific beans. Two ways to autoproxy beans: ■ Basic autoproxying of beans based on advisor beansdeclared in the Spring context—The advisor’s pointcutexpression is used to determine which beans and whichmethods will be proxied. ■ Autoproxying based on @AspectJ annotation-drivenaspects—The pointcut specified on the advice containedwithin the aspect will be used to choose which beans andmethods will be proxied.
  • 64. Basic Autoproxying Spring comes with a handy implementation of BeanPostProcessorcalled DefaultAdvisorAutoProxyCreator, which automaticallychecks to see whether an advisor’s pointcut matches a bean’smethods and replaces that bean’s definition with a proxyautomatically that applies the advice. The DefaultAdvisorAutoProxyCreator is used with the following<bean> in the Spring context: <beanclass="org.springframework.aop.framework.autoproxy. ➥ DefaultAdvisorAutoProxyCreator" /> The bean doesn’t have an id as it is never referred directly. The Spring container recognizes it as a BeanPostProcessor andputs it to work creating proxies. When the DefaultAdvisorAutoProxyCreator is declared, its nolonger required to declare ProxyFactoryBeans in the Springcontext give the beans weird names that end with target.
  • 65. Autoproxying @AspectJ aspects AspectJ 5 is the ability to annotate POJO classes to be aspectssprinkling a few annotations around. The @Pointcut annotation is used to define a reusable pointcut withinan @AspectJ aspect. The name of the pointcut is derived from the name of the method towhich the annotation is applied. The value given to the @Pointcut annotation is an AspectJ pointcutexpression. @Pointcut("execution(* *.perform(..))") public void performance() {} Each of the audience’s methods has been annotated with adviceannotations. The @Before annotation applied to the methods to indicate that themethods are before advice. The @AfterReturning annotation indicates that the method is anafterreturning advice method. The @AfterThrowing annotation placed on a method in order to becalled if any exceptions are thrown during the performance. The name of the method pointcut is given as the value parameter to allof the advice annotations which tells each advice method where itshould be applied. For example: @Before("performance()")
  • 66. Autoproxying @AspectJ aspects An autoproxy bean in the Spring context which knows to turn@AspectJ-annotated beans into proxy advice must be declared. Spring comes with an autoproxy creator class calledAnnotationAwareAspectJAutoProxyCreator and also provides acustom configuration element in the aop namespace making it easierto register the autoproxy creator class in the Spring context. <aop:aspectj-autoproxy /> It creates an AnnotationAwareAspectJAutoProxyCreator in the Springcontext and automatically proxy beans whose methods match thepointcuts defined with @Pointcut annotations in @Aspectannotatedbeans. The <aop:aspectj-autoproxy> element is used by including the aopnamespace in the Spring configuration file. AnnotationAwareAspectJAutoProxyCreator also creates proxies basedon classic Spring advisors. The @around annotation before the method isn’t enough to provide aproceed() method to call. Therefore, methods that are to be aroundadvice must take a ProceedingJoinPoint object as an argument andthen call the proceed() method on that object.
  • 67. Spring 2.0’s AOP configuration elements Spring’s AOP configuration elements can be used to turn anyclass into an aspect without the source code of the class.AOP configurationelementPurpose<aop:advisor> Defines an AOP advisor.<aop:after> Defines an AOP after advice (regardless of whether theadvised method returns successfully).<aop:after-returning> Defines an AOP after-returning advice.<aop:after-throwing> Defines an AOP after-throwing advice.<aop:around> Defines an AOP around advice.<aop:aspect> Defines an aspect.<aop:before> Defines an AOP before advice.<aop:config> The top-level AOP element. Most <aop:*> elements mustbe contained within <aop:config>.<aop:pointcut> Defines a pointcut.
  • 68.  <beans xmlns=………………….. /> <aop:config> <aop:aspect ref="audience"> <aop:pointcut id="performance“ expression="execution(* *.perform(..))" /> <aop:before method="takeSeats" pointcut-ref="performance" /> <aop:before method="turnOffCellPhones" pointcut-ref="performance" /> <aop:after-returning method="applaud" pointcut-ref="performance" /> <aop:after-throwing method="demandRefund" pointcut-ref="performance" /> </aop:aspect> </aop:config> </beans>
  • 69. Injecting AspectJ aspects AspectJ offers many types of pointcuts that are not possiblewith Spring AOP. AspectJ aspects are independent of Spring. If an aspect depends on one or more classes when executingits advice, one can instantiate those collaborating objectswith the aspect itself or using Spring’s dependency injectionto inject beans into AspectJ aspects. To use Spring’s dependency injection to inject collaboratorsinto an AspectJ aspect, the aspect is declared as a <bean> inSpring’s configuration. <bean class="com.springinaction.springidol.JudgeAspect" factory-method="aspectOf"> <property name="criticismEngine" ref="criticismEngine" /> </bean>
  • 70. A Sample AspectJ implementation package com.springinaction.springidol; public aspect JudgeAspect { public JudgeAspect() {} pointcut performance() : execution(* perform(..)); after() returning() : performance() { System.out.println(criticismEngine.getCriticism()); } // injected private CriticismEngine criticismEngine; public void setCriticismEngine(CriticismEngine criticismEngine) { this.criticismEngine = criticismEngine; } }
  • 71. Injecting AspectJ aspects Spring beans are instantiated by the Springcontainer—but AspectJ aspects are created by theAspectJ runtime. All AspectJ aspects provide a static aspectOf()method that returns the singleton instance of theaspect to get an instance of the aspect, using thefactory-method to invoke the aspectOf() method. Spring retrieves a reference to the aspect through theaspectOf() factory method and then performsdependency injection on it as prescribed by the<bean> element.

×