What is AOP
AOP-oriented tangent programming
adopt the horizontal extraction mechanism to replace the traditional longitudinal inheritance system repetitive code (performance monitoring, transaction management, security check, cache)
Spring AOP uses a pure Java implementation that does not require a dedicated compilation process and ClassLoader to weave the enhanced code into the target class at run time by proxy
ASPECJ is an AOP framework based on the Java language, Spring2.0, Spring AOP introduces support for aspect, ASPECTJ extends the Java language, provides a dedicated compiler, and provides horizontal code weaving at compile time.
AOP underlying principles
Is the agent mechanism:
* Dynamic Agent: (used in JDK)
* JDK Dynamic Proxy, the class generation agent that implements the interface.
Spring's AOP Proxy
JDK Dynamic Agent: A class generation agent that implements an interface. A proxy object cannot be generated without a class that implements the interface.
Cglib proxy mechanism: generating proxies for classes
Conclusion: TheSpring Framework, if the class implements an interface, uses the JDK's dynamic proxy to generate the proxy object, and if the class does not implement any interfaces, use Cglib to generate the proxy object.
Terminology of AOP
Joinpoint (connection point): The so-called connection point refers to the points that are intercepted. In spring, these points refer to methods because spring only supports connection points of method types .
Pointcut (pointcut): The so-called pointcut is the definition of which joinpoint we want to intercept.
Advice (Notification/enhancement): The so-called notification refers to the interception to Joinpoint after the thing to do is to inform. Notification is divided into pre-notification, post-notification, exception notification, final notification, surround notification (slice to complete the function)
Introduction (Introduction): Introduction is a special kind of notification without modifying the class code, Introduction can dynamically add properties or methods to the class at run time.
Target object: The target object of the agent
Weaving (weaving): Refers to the process of applying an enhancement to a target object to create a new proxy object.
Spring is woven with dynamic agents, while ASPECTJ is woven into the stage with the compile-time and class-loaded
Proxy: When a class is augmented by AOP, it produces a result proxy class
Aspect (Tangent): A combination of pointcuts and notifications (referrals)
Facets without tangency
Spring follows the notification advice at the connection point location of the target method, notifying advice to be divided into five categories
Pre-notification: Org.springframework.aop.MethodBeforeAdvice, enforcing enhancements prior to target method execution
Post notification: Org.springframework.aop.AfterReturningAdvice, enforcing enhancements after target method execution
Surround notification: Org.aopalliance.intercept.MethodInterceptor, implementing enhancements before and after the target method execution
Exception throw notification: Org.springframework.aop.ThrowsAdvice, enforcing enhancements after method throws an exception
Referral notification: Org.springframework.aop.IntroductionInterceptor, adding some new methods and properties to the target class
Types of slices in spring:
Traditional facets in the advisor:spring.
Aspect: There is a combination of a pointcut and a notification
Advisor: A combination of multiple pointcuts and multiple notifications
Advisor : Represents a general facet, advice itself is a facet that intercepts all methods of the target class (* facets without tangency)
Pointcutadvisor : Represents a tangent plane that can specify which methods of the target class have tangent slices to intercept for a method
Introductionadvisor : Represents an introduction plane, using a cut-off for referral notification (not required)
Instance of a slice without tangency
Import the appropriate JAR package: Spring Development Foundation Package, Spring-aop-4.3.7.release.jar, Aopalliance-1.0.jar (AOP Alliance package)
Write an interface to customer:
Package publicinterface Customerdao { publicvoid Add (); Public void Delete (); Public void update (); Public void find ();}
Write the implementation class Customerimpl:
PackageCom.js.aopStu; Public classCustomerimplImplementsCustomerdao {@Override Public voidAdd () {System.out.println ("Add Customer ..."); } @Override Public voidDelete () {System.out.println ("Delete Customer ..."); } @Override Public voidUpdate () {SYSTEM.OUT.PRINTLN ("Modify Customer ..."); } @Override Public voidfind () {System.out.println ("Query Customer ..."); } }
write the enhanced code. Create a new class Mybeforeadvice, as an example of a predecessor enhancement
PackageCom.js.aopStu;ImportJava.lang.reflect.Method;ImportOrg.springframework.aop.MethodBeforeAdvice;/*** Pre-enhancement * implements the specified interface *@authorHDB **/ Public classMybeforeadviceImplementsmethodbeforeadvice{/*** Method: How to execute * args: Parameters * Target: target object*/@Override Public voidBefore (method, object[] args, Object target)throwsthrowable {System.out.println ("Pre-enhancement ..."); } }
Configure the proxy generation proxy class , based on the Proxyfactorybean class, which automatically selects the dynamic agent using the JDK or the Cglib proxy.
Configuration applicationcontext.xml:
<?xml version= "1.0" encoding= "UTF-8"? ><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"Xmlns:util= "Http://www.springframework.org/schema/util"xsi:schemalocation="http//Www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp//Www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util.xsd"><!--define the target object--><bean id= "Customerdao"class= "Com.js.aopStu.CustomerImpl" ></bean><!--definition enhancement--><bean id= "Beforeadice"class= "Com.js.aopStu.MyBeforeAdvice" ></bean> <!--Spring supports configuration to generate proxies, based on Proxyfactorybean class, The bottom level automatically selects the dynamic agent using the JDK or the Cglib agent--<bean id= "Customerdaoproxy"class="Org.springframework.aop.framework.ProxyFactoryBean> <!--Setting target objects--<property name=Target"Ref="Customerdao"></property> <!--settings implemented interface, value writes the full path of the interface---<property name="proxyinterfaces"Value="Com.js.aopStu.CustomerDao"></property> <!--configuration needs to be intercepted, must be value, where all methods in Customerdao are intercepted---<property name="Interceptornames"Value="Beforeadice"></property> </bean></beans>
We need to configure some properties that are not required to be set.
Lproxyfactorybean Common configurable Properties target: Proxy target object proxyinterfaces: interface to be implemented by the agent • If multiple interfaces can be assigned using the following format
<list>
<value></value>
....
</list>
Proxytargetclass: When set to True for a class proxy instead of an interface, use the Cglib proxy interceptornames: Advice singleton that needs to be woven into the target: Returns whether the proxy is a single instance, the default is singleton · Optimize: When set to true, forces the use of Cglib (Proxyinterfaces, Proxytargetclass are mutually exclusive and cannot exist simultaneously)
To write a test class:
PackageCom.js.aopStu;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Qualifier;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith (springjunit4classrunner. Class) @ContextConfiguration ("Classpath:applicationContext.xml") Public classTestAOPDemo1 { @Autowired @Qualifier ( "Customerdaoproxy")PrivateCustomerdao Customerdao; //without the use of enhanced cases@Test Public voidDemo1 () {customerdao.add (); Customerdao.delete (); Customerdao.find (); Customerdao.update (); }}
Tangent slices (commonly used) implement a class with the Pointcutadvisor, which has two interfaces: 1,Defaultpointcutadvisor: The most commonly used facet type, which can be defined by any combination of pointcut and advice 2,Regexpmethodpointcutadvisor: Construction
Regular expression tangent plane,
The general use of this。 Slice instance with tangent point
Create a new DAO that creates the Proxied object:
PackageCom.js.demo3;/*** Target Object *@authorHDB **/ Public classOrderdao { Public voidAdd () {System.out.println ("Add Order ..."); } Public voidDelete () {System.out.println ("Delete Order ..."); } Public voidUpdate () {SYSTEM.OUT.PRINTLN ("Modify Order ..."); } Public voidfind () {System.out.println ("Inquiry order ..."); }}
Write the enhanced class, this time using surround enhancement:
PackageCom.js.demo3;ImportOrg.aopalliance.intercept.MethodInterceptor;Importorg.aopalliance.intercept.MethodInvocation;/*** Enhanced class * using surround Enhancement *@authorHBD **/ Public classMyaroundadviceImplements methodinterceptor{@Override PublicObjectInvoke(Methodinvocation methodinvocation)throwsthrowable {System.out.println ("Surround-forward enhancement = = ="); Object Object=methodinvocation.proceed ();//methods for executing target objectsSYSTEM.OUT.PRINTLN ("surround enhancement = = = ="); returnobject; } }
Build agent: By configuration:
<?xml version= "1.0" encoding= "UTF-8"? ><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"Xmlns:util= "Http://www.springframework.org/schema/util"xsi:schemalocation="http//Www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp//Www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util.xsd"><!--tangent--><!--define the target object--><bean id= "OrderDao1"class= "Com.js.demo3.OrderDao" ></bean><!--definition enhancement--><bean id= "Aroundadvice"class= "Com.js.demo3.MyAroundAdvice" ></bean><!--defining tangent plane:--><bean id= "Mypointcutadvisor"class="Org.springframework.aop.support.RegexpMethodPointcutAdvisor> <!--define expressions that specify which methods to perform interception--<!--. Any character * any--<!--<property name= "pattern" value= ". *"/>--<!--<property name= "pattern" va Lue= "cn\.itcast\.spring3\.demo4\. orderdao\.add.* "/>-<!--<property name=" pattern "value=". *add.* "></property>-<pro Perty name= "Patterns"Value=". *add.*,.*find.*"></property> <!--App-enhanced-<property name="Advice"Ref="Aroundadvice"/></bean><!--define the Build proxy object--><bean id="Orderdaoproxy"class= "Org.springframework.aop.framework.ProxyFactoryBean" > <!--Configuration Target--<property name= "Target"Ref="OrderDao1></property> <!--agents for classes--<property name= "Proxytargetclass"Value="true></property> <!--apply an enhanced-<property name= on the targetInterceptornames"Value="Mypointcutadvisor"></property></bean></beans>
To write a test class:
PackageCom.js.demo3;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Qualifier;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith (springjunit4classrunner. Class) @ContextConfiguration ("Classpath:applicationContext.xml") Public classTestAOPDemo1 {
@Autowired @Qualifier ( "Orderdaoproxy")PrivateOrderdao Orderdao;
@Test Public voiddemo1 () {orderdao.add (); Orderdao.delete (); Orderdao.find (); Orderdao.update (); }}
Spring AOP Learning