[Spring Frame] Spring AOP Basics Primer Summary One.

Source: Internet
Author: User
Tags aop throwable

Objective:
There are two previous articles on spring Ioc/di and the use of XML and annotations to develop the case, let's comb the spring's other core AOP.

One, what is AOP

In the software industry, AOP is the abbreviation for Aspect oriented programming, which means: face-cutting programming, through the pre-compilation method and runtime dynamic agent to implement the unified maintenance of the program functions of a technology. AOP is a continuation of OOP, a hotspot in software development, an important content in the spring framework, and a derivative model of functional programming. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.

AOP takes the horizontal extraction mechanism instead of the repetitive code of the traditional vertical inheritance system.

Spring AOP uses a pure Java implementation that does not require a specialized compilation process and ClassLoader to weave the enhanced code into the target class at run time through a proxy approach.

Ii. terminology in the development of AOP

    1. 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.
    2. Pointcut (pointcut): The so-called pointcut is the definition of which joinpoint we want to intercept.
    3. 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 )
    4. Introduction (Introduction): Introduction is a special kind of notification without modifying the class code, Introduction can dynamically add methods or field to the class at run time.
    5. Target object: The target object of the agent
    6. Weaving (weaving): refers to the process of applying an enhancement to a target object to create a new proxy object.
      Spring uses dynamic proxy weaving, while the ASPECTJ is woven into the stage with a compile-time weave and class-loaded.
    7. Proxy : When a class is woven into an AOP, it produces a result proxy class Aspect (tangent): a combination of pointcuts and notifications (referrals)

Third, dynamic agent
Spring AOP Core technology is the use of Java Dynamic Agent technology, here is a simple summary of the JDK and cglib two kinds of dynamic agent mechanism.

Concept:
When an object (client) cannot or does not want to refer directly to another object (the target object), then the proxy mode can be applied to build a bridge between the two-proxy object. Depending on the creation period of the proxy object, there are two types:
Static proxy: The programmer has written the proxy object class beforehand, already existed before the program release;
Dynamic Proxy: After the application is published, the proxy object is created dynamically.
One dynamic agent can be divided into: jdk/cglib dynamic agent.


3.1 JDK Dynamic Agent

At this point, the proxy object and the target object implement the same interface, the target object as a property of the proxy object, the specific interface implementation, you can call the target object corresponding method before and after adding other business processing logic.

The proxy mode needs to specify a specific target object when it is actually used, and if you add a proxy class for each class, it will cause a lot of classes, and if you don't know the specific class, how do you implement the proxy mode? This leads to dynamic proxies.

The JDK dynamic agent can only generate proxies for classes that implement an interface .
code example:
Userservice.java:

Public interface UserService {public    void Save ();    public void Update ();    public void Delete ();    public void Find ();}

Userserviceimpl.java:

1 public class Userserviceimpl implements UserService {2  3     @Override 4 public     void Save () {5         System.out. println ("Save user ..."); 6     } 7  8     @Override 9 public     void Update () {         System.out.println ("Modify user ...")     }12     OVERRIDE14 public     Void Delete () {         System.out.println ("Delete user ...")     }17     @Override19     public void Find () {         System.out.println ("Query user ...");     }22 23}

Myjdbproxy.java:

 1/** 2 * Implement agent mechanism using JDK dynamic Proxy 3 * 4 */5 public class Myjdbproxy implements invocationhandler{6 7 private UserService UserService; 8 9 public Myjdbproxy (UserService userservice) {this.userservice = userservice;11}12 Rservice Createproxy () {14//proxy for Generation UserService: UserService userserviceproxy = (userservice) proxy.newpro Xyinstance (Userservice.getclass (). getClassLoader (), Userservice.getclass (). g Etinterfaces (), this), return userserviceproxy;19}20 @Override22 public Object Invoke (Object Pro XY, method, object[] args) throws Throwable {24//determines if the Save method is: + if ("Save". Equals (Me Thod.getname ())) {26//Enhanced: System.out.println ("permission check ==========="); return method.in Voke (UserService, args);}30 return Method.invoke (UserService, args);}32} 

Springdemo.java Test class:

1 public class SpringDemo1 {2  3     @Test 4     //Call way without proxy 5 public     void Demo1 () {6         //Create target object 7         use Rservice userservice = new Userserviceimpl (); 8          9 Userservice.save ();         userservice.update ();         userservice.delete (         ); Userservice.find ();     }14     @Test16     //Use agent: public     void Demo2 () {         //Create target object 19         UserService userservice = new Userserviceimpl ();         UserService proxy = new Myjdbproxy (userservice). Createproxy (); Proxy.save (); Proxy.update (         );         Proxy.delete ();         proxy.find ();     }27}


3.2 CGLIB Dynamic Agent

The CGLIB (CODE generlize LIBRARY) Proxy is a proxy for the class, primarily generating a subclass of the specified class that overrides all of the methods, so that the class or method cannot be declared final.

If the target object does not implement the interface, the Cglib proxy will be used by default;

If the target object implements an interface, you can force the proxy to be implemented using Cglib (add the Cglib Library and include <aop:aspectj-autoproxy proxy-target-class= "true" in the spring configuration/>
code example:
Customerservice.java:

1 public class CustomerService {2 public     void Save () {3         System.out.println ("Save Customer ..."); 4     } 5 public     void Update () {6         System.out.println ("Modify Customer ..."); 7     } 8 public     void Delete () {9         System.out.println ("Delete Customer ...");     }11 public     Void Find () {12         System.out.println ("Query Customer ...");     14}

Mycglibproxy.java:

 1/** 2 * Generate proxy using cglib 3 * 4 */5 public class Mycglibproxy implements methodinterceptor{6 7 private Customerserv Ice CustomerService;      8 9 public Mycglibproxy (CustomerService customerservice) {this.customerservice = customerservice;11}12         Public CustomerService Createproxy () {14//Create Core class: Enhancer enhancer = new Enhancer (); 16 Set Parent class: Enhancer.setsuperclass (Customerservice.getclass ()); 18//Set callback: Enhancer.setcallba         CK (this); 20//Create agent: CustomerService Customerserviceproxy = (customerservice) enhancer.create (); 22 Return customerserviceproxy;23}24 @Override26 public Object Intercept (object proxy, method, Obje             Ct[] arg,27 methodproxy methodproxy) throws throwable {"Delete". Equals (Method.getname ())) {29             Object obj = methodproxy.invokesuper (proxy, Arg); System.out.println ("Logging =========="); 31Return obj;32}33 return methodproxy.invokesuper (proxy, Arg); 34}35} 

Springdemo.java Test class:

1 public class SpringDemo2 {2  3     @Test 4 public     void Demo1 () {5         customerservice customerservice = new Cust Omerservice (); 6         Customerservice.save (); 7         customerservice.update (); 8         Customerservice.delete (); 9         Customerservice.find ();     }11     @Test13 public     void Demo2 () {         customerservice CustomerService = new CustomerService ();         //Generation Agent: CustomerService proxy         = new Mycglibproxy ( CustomerService). Createproxy ();         proxy.save ();         proxy.update ();         proxy.delete ();         Proxy.find ();     }22}

AOP includes facets (aspect), notifications (advice), Connection points (Joinpoint), which is accomplished by adding a notification to the target object's agent before and after the connection point to complete a unified slice operation.

Four, spring's traditional AOP: an agent based on the Proxyfactorybean approach

4.1 Spring's notification type

Pre-notification Org.springframework.aop.MethodBeforeAdvice

Enforcing enhancements prior to target method execution

Post Notification Org.springframework.aop.AfterReturningAdvice

Enforcing enhancements after the target method executes

Surround Notification Org.aopalliance.intercept.MethodInterceptor

Implementation enhancements before and after the target method execution

Exception Throw Notification Org.springframework.aop.ThrowsAdvice

Enforcing enhancements after a method throws an exception

4.2 Spring's tangent type

Advisor: Represents a general aspect, advice itself is a facet, which intercepts all methods of the target class. (Facets without pointcuts, all methods in the default enhanced Class)

Pointcutadvisor: Represents a tangent facet that specifies which methods of the target class are intercepted. (Facets with pointcuts)


Quick start of 4.3 spring traditional AOP

4.3.1 development of Facets without pointcuts

AOP development involves the introduction of related jar packages:
  

Productservice.java:

View Code

Productserviceimpl.java:

View Code

Mybeforeadvice.java:

View Code

Springdemo.java Test class:

View Code


  4.3.1 Development with Pointcuts

Orderservice.java:

View Code

Myaroundadvice.java:

View Code

Springdemo.java Test class:

View Code


Applicationcontext.xml configuration file:

View Code


Based on the Spring Factorybean Agent summary:

Spring uses a different proxy approach depending on whether the class implements the interface:

* Implementation interface: JDK dynamic agent.

* No interface implemented: Cglib generation agent.

The process of generating agents based on Proxyfactorybean is not particularly desirable:

* Configuration cumbersome, unfavorable for maintenance.

* You need to configure a Proxyfactorybean for each class that needs to be enhanced.

Five, Spring's traditional AOP: based on automatic proxy

5.1 automatic proxy and Proxyfactorybean agent-based comparison:

Automatic proxies are based on beanpostprocessor (the factory hooks mentioned in the previous article).

* The proxy object is already in the process of generating the class.

Agent based on Proxyfactorybean mode:

* The target object is first and the agent is generated according to the target object.

5.2 How to Auto Proxy:
Beannameautoproxycreator : Automatic proxy based on Bean name

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3 x Mlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemalocation= "Http://www.springframework.org/schema  /beans http://www.springframework.org/schema/beans/spring-beans.xsd "> 5 6 <!--Configuration target Object--7 <bean Id= "Productservice" class= "Cn.augmentum.aop.demo3.ProductServiceImpl" ></bean> 8 <bean id= "OrderService "class=" Cn.augmentum.aop.demo4.OrderService "/> 9 <!--configuration pre-enhancement-->11 <bean id=" Mybeforeadvice "C lass= "Cn.augmentum.aop.demo3.MyBeforeAdvice"/>12 <bean id= "Myaroundadvice" class= " Cn.augmentum.aop.demo4.MyAroundAdvice "/>13 <!--automatic proxy based on bean name-->15 <bean class=" Org.springfram Ework.aop.framework.autoproxy.BeanNameAutoProxyCreator ">16 <property name=" Beannames "value=" *service "/> <property name= "Interceptornames" value= "MybefoReadvice "/>18 </bean>19 </beans> 

Defaultadvisorautoproxycreator : Automatic proxy based on slice information
 1 <beans xmlns= "Http://www.springframework.org/schema/beans" 2 xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-inst ance "3 xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beans/spring-beans.xsd "> 4 5 <!--Configuration target Object--6 <bean id=" Productservice "class=" CN.AUGMENTUM.AOP. Demo3. Productserviceimpl "></bean> 7 <bean id=" OrderService "class=" Cn.augmentum.aop.demo4.OrderService "/>      8 9 <!--configuration pre-enhancement-->10 <bean id= "Mybeforeadvice" class= "Cn.augmentum.aop.demo3.MyBeforeAdvice"/>11     <bean id= "Myaroundadvice" class= "Cn.augmentum.aop.demo4.MyAroundAdvice"/>12 <!--configuration facets information-->14 <bean id= "advisor" class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor" >15 <property N Ame= "Advice" ref= "Myaroundadvice"/>16 <!--<property name= "pattern" value= "cn\.augmentum\.aop\.demo4\. Orderservice\.save "/>--&Gt;17 <property name= "Patterns" value= "cn\.itcast\.aop\.demo4\". Orderservice\.save,cn\.augmentum\.aop\.demo3\. Productservice\.update "/>18 </bean>19 <!--configuration based on facets information automatic proxy-->21 <bean class=" org.spring Framework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator "/>22 </beans>

[Spring Frame] Spring AOP Basics Primer Summary One.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.