Make spring no longer difficult to understand-AOP article

Source: Internet
Author: User

What is AOP

AOP (aspect-orientedprogramming, aspect-oriented programming) can be said to complement and improve OOP (object-oriented programing, object-oriented programming). OOP allows you to define relationships from top to bottom, but it is not appropriate to define a left-to-right relationship. such as logging capabilities. Log code is often spread horizontally across all object hierarchies, and has nothing to do with the core functionality of the objects it spreads to. This irrelevant code scattered around is called crosscutting (cross-cutting) code, and in OOP design, it leads to a lot of duplication of code, rather than the reuse of individual modules.

What is Aop.png

AOP, on the contrary, uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, called "Aspect", which is the facet. The so-called "aspect", in a nutshell, is to encapsulate the logic or responsibility that is not related to the business, but for the common invocation of the business module, to reduce the duplication of code in the system, to reduce the coupling between modules, and to facilitate future operability and maintainability.

AOP Usage Scenarios

AOP Framework Types

    • Aspectj

    • JBoss AOP

    • Spring AOP

There are a lot of things you can do with AOP.

    • Performance monitoring, which records the call time before and after the method call, and the method performs too long or timed out the alarm.

    • The cache proxy, which caches the return value of a method, is fetched directly from the cache the next time the method is executed.

    • Software cracking, using AOP to modify the judgment logic of software validation classes.

    • Log the system log before and after the method execution is logged.

    • Workflow systems, where the workflow system needs to mix business code and process engine code together, we can use AOP to separate it and dynamically hook up the business.

    • The permission is validated before the method executes to verify that there is permission to execute the current method, without throwing no permission to execute the exception that is captured by the business code.

Look at the difference between traditional coding and using AOP

3 Kinds of log processing. png

Core Concepts

Some of the terminology commonly used to describe AOP are notifications (ADIVCE), pointcuts (Pointcut), Connection points (join point), facets (Aspect), ingestion (Introduction), weaving (Weaving), Notifications (Advice), and so on.

AOP important concepts. png

Simple example

The annotation-based approach is more concise and convenient than the XML configuration.

1@AspectpublicclassTransactiondemo {2     3@Pointcut (value= "Execution (* com.yangxin.core.service.*.*.* (..))") Public voidPoint () {4         5     }6     7@Before (value= "point ()") Public voidbefore () {8SYSTEM.OUT.PRINTLN ("Transaction Begin");9     }Ten      One@AfterReturning (value = "point ()") Public voidAfter () { ASYSTEM.OUT.PRINTLN ("Transaction Commit"); -     } -      the@Around ("point ()") Public voidAround (Proceedingjoinpoint joinpoint)throwsthrowable{ -SYSTEM.OUT.PRINTLN ("Transaction Begin"); - joinpoint.proceed (); -SYSTEM.OUT.PRINTLN ("Transaction Commit"); +     } -}

Configured in the Applicationcontext.xml.

</><= "transactiondemo"= " Com.yangxin.core.transaction.TransactionDemo "/>
Spring AOP principle

As you can tell by the previous introduction, an AOP proxy is actually an object that is dynamically generated by the AOP framework, which can be used as a target object. The AOP proxy contains all the methods of the target object, but the methods in the AOP proxy differ from the methods of the target object: The AOP method adds enhanced processing to a particular pointcut and recalls the method of the target object.

Methods of the agent and the target object. png

Spring's AOP agents are generated and managed by spring's IOC container, and their dependencies are managed by the IOC container. Therefore, the AOP proxy can use the other Bean instances in the container directly as the target, which can be provided by the dependency injection of the IoC container.

When AOP is developed, there are only 3 parts that require programmer involvement:

    • Define common business components.

    • Define Pointcuts, where a pointcut can cross-cut multiple business components.

    • Define enhanced processing, which is the processing action that the AOP framework weaves into ordinary business components.

To clarify the relationship, first a class diagram.

The main AOP component in spring. png

Two kinds of dynamic proxy methods

Spring implements the AOP by default by the dynamic proxy mechanism, which uses the cglib mechanism when the dynamic proxy is unavailable (the proxy class has no interfaces).

Spring provides two ways to generate proxy objects: Jdkproxy and Cglib, which are generated by aopproxyfactory depending on the configuration of the Advisedsupport object. The default policy is to use the JDK dynamic Agent technology if the target class is an interface, otherwise use Cglib to generate the proxy.

JDK Dynamic Agent

    • The JDK dynamic agent mainly involves two classes in the Java.lang.reflect package: Proxy and Invocationhandler. Invocationhandler is an interface that dynamically compiles crosscutting logic and business logic by implementing the interface to define crosscutting logic and invoking the code of the target class through a reflection mechanism.

    • Proxy uses Invocationhandler to dynamically create an instance that conforms to an interface, generating a proxy object for the target class.

Cglib Dynamic Agent

    • Cglib, called the Code Generation Library, is a powerful, high-performance, high-quality codebase that can extend Java classes and implement Java interfaces at runtime, Cglib encapsulates ASM, and can dynamically generate new classes at run time. Compared to the JDK dynamic agent: The JDK Creation Agent has a limitation that only proxy instances can be created for the interface, whereas for classes that do not have a business method defined through an interface, dynamic proxies are created through Cglib.

Knowledge development

Through the above analysis, whether people have a familiar feeling, seems to be similar to the function of interceptors, filters. So the question is, what is the relationship between AOP and interceptors and filters?

Let's review the interceptors and filters first. As a user's test, TestFilter1 and TestFilter2 are registered in Web. Xml. Baseinterceptor and Testinterceptor are then configured in the spring configuration file. The results are as shown. As you can see, interceptors and filters both cut through the business approach, seemingly conforming to the idea of AOP.

Interceptors and filters. png

Filter Filters: Blocks Web Access URL addresses.
Interceptor Interceptor: Intercepts the URL at the end of the. Action, blocking access to the action.
Spring AOP Interceptor: can only intercept access to spring management beans (Business layer Service)

Interceptors and filters. png

Reference Document: Https://mp.weixin.qq.com/s/6WK2oV-vaqPGQpIIR5UeHA

Make spring no longer difficult to understand-AOP article

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.