The implementation principle of Spring AOP

Source: Internet
Author: User

Original source: Listen

AOP (Aspect Orient programming), which we generally call aspect-oriented programming, complements the object-oriented approach to the crosscutting concerns that are distributed across modules in the system, such as transaction management, logging, caching, and so on. The key to the AOP implementation is the AOP proxy, which is automatically created by the AOP framework, which is mainly divided into static agent and dynamic agent, static proxy is ASPECTJ, and dynamic agent is represented by spring AOP. This article will analyze and introduce the implementation of ASPECTJ and spring AOP respectively.

Implementing AOP with AspectJ's compile-time enhancements

As mentioned earlier, ASPECTJ is an enhancement of static proxies, so-called static proxies are the AOP framework that generates an AOP proxy class during the compilation phase, and therefore is also known as compile-time enhancement.

For example, let me give you a sample. First of all we have a common Hello class

12345678910 public class Hello {    public void sayHello() {        System.out.println("hello");    }    public static void main(String[] args) {        Hello h = new Hello();        h.sayHello();    }}

Write a aspect using ASPECTJ

1234567 public aspect TxAspect {    void around():call(void Hello.sayHello()){        System.out.println("开始事务 ...");        proceed();        System.out.println("事务结束 ...");    }}

This simulates a transaction scenario, similar to spring's declarative transaction. Compiling with ASPECTJ compiler

1 ajc -d . Hello.java TxAspect.aj

Once the compilation is complete, run this Hello class and you can see the following output

123 开始事务 ...hello事务结束 ...

Obviously, AOP is already in effect, so how does ASPECTJ add new functionality to the Hello class without modifying the Hello class?

Look at the compiledHello.class

12345678910111213 public class Hello {    public Hello() {    }    public void sayHello() {        System.out.println("hello");    }    public static void main(String[] args) {        Hello h = new Hello();        sayHello_aroundBody1$advice(h, TxAspect.aspectOf(), (AroundClosure)null);    }}

As you can see, this analogy turns out to be a Hello.java bit more code, which is the static proxy for ASPECTJ, which weaves the aspect into Java bytecode at compile time, which is the augmented AOP object when it runs.

12345 public void ajc$around$com_listenzhangbin_aop_TxAspect$1$f54fe983(AroundClosure ajc$aroundClosure) {        System.out.println("开始事务 ...");        ajc$around$com_listenzhangbin_aop_TxAspect$1$f54fe983proceed(ajc$aroundClosure);        System.out.println("事务结束 ...");    }

The logic of execution can be seen more clearly from the aspect compiled class file. proceedmethod is the callback that executes the method in the proxy class.

Using Spring AOP

Unlike static proxies for ASPECTJ, the dynamic proxy used by Spring AOP, the so-called dynamic Proxy means that the AOP framework does not modify bytecode, but instead generates an AOP object temporarily in memory for the method, which contains all the methods of the target object. And the method of the original object is enhanced with the specific pointcut.

There are two main ways of dynamic Proxy in Spring AOP, JDK dynamic agent and Cglib dynamic agent. The JDK dynamic agent receives the Proxied class through reflection, and requires that the class being proxied must implement an interface. The core of a JDK dynamic agent is InvocationHandler interfaces and Proxy classes.

If the target class does not implement an interface, spring AOP chooses to use Cglib to dynamically proxy the target class. CGLIB (Code Generation Library) is a code-generated class library that dynamically generates subclasses of a class at run time, noting that CGLIB is a dynamic proxy that is done by inheritance, so if a class is marked final , Then it is not possible to use Cglib to do dynamic proxies.

To verify the above statement, a simple test can be done. First, test the implementation of the interface.

Define an interface

123 publicinterfacePerson {    String sayHello(String name);}

Implementation class

123456789101112131415 @Componentpublic class Chinese implements Person {    @Timer    @Override    public String sayHello(String name) {        System.out.println("-- sayHello() --");        return name + " hello, AOP";    }    public void eat(String food) {        System.out.println("我正在吃:" + food);    } }

The @Timer annotations Here are a general note that I define myself to mark Pointcut.

Define Aspect

12345678910111213 @Aspect@Componentpublic class AdviceTest {    @Pointcut("@annotation(com.listenzhangbin.aop.Timer)")    public void pointcut() {    }    @Before("pointcut()")    public void before() {        System.out.println("before");    }}

Run

123456789101112131415161718 @SpringBootApplication@RestControllerpublic class SpringBootDemoApplication {    //这里必须使用Person接口做注入    @Autowired    private Person chinese;    @RequestMapping("/test")    public void test() {        chinese.sayHello("listen");        System.out.println(chinese.getClass());    }    public static void main(String[] args) {        SpringApplication.run(SpringBootDemoApplication.class, args);    }}

Output

123 before-- sayHello() --classcom.sun.proxy.$Proxy53

You can see that the type is, that is com.sun.proxy.$Proxy53 , the proxy class mentioned earlier, so here Spring AOP uses the JDK's dynamic proxy.

Then look at the case where the interface is not implemented, modify the Chinese class

123456789101112131415 @Componentpublic class Chinese {    @Timer//    @Override    public String sayHello(String name) {        System.out.println("-- sayHello() --");        return name + " hello, AOP";    }    public void eat(String food) {        System.out.println("我正在吃:" + food);    }}

Run

123456789101112131415161718 @SpringBootApplication@RestControllerpublic class SpringBootDemoApplication {    //直接用Chinese类注入    @Autowired    private Chinese chinese;    @RequestMapping("/test")    public void test() {        chinese.sayHello("listen");        System.out.println(chinese.getClass());    }    public static void main(String[] args) {        SpringApplication.run(SpringBootDemoApplication.class, args);    }}

Output

123 before-- sayHello() --classcom.listenzhangbin.aop.Chinese$$EnhancerBySpringCGLIB$$56b89168

You can see that the class is cglib enhanced, which is the dynamic proxy. The Cglib agent here is the proxy for spring AOP, the so-called AOP Proxy, where the AOP proxy class dynamically weaves the enhanced processing in the pointcut.

Summary

ASPECTJ enhances the target object at compile time, the dynamic agent of Spring AOP is dynamically enhanced at each run time, and the AOP proxy object is generated, the difference is that the timing of generating AOP proxy object is different, and the static proxy method of ASPECTJ has better performance. However, ASPECTJ requires a specific compiler for processing, and spring AOP does not require specific compiler processing.

Reference:
    • "Spring AOP Implementation principle and CGLIB application"
    • The implementation principle of Spring container AOP--Dynamic agent
    • The bottom-up implementation of AOP-cglib dynamic agents and JDK dynamic agents

From:http://www.importnew.com/24305.html

The implementation principle of Spring AOP

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.