Aspect-oriented Programming), can be said to be OOP (object-oriented Programming, object-oriented Programing) perfect and complement. OOP allows you to define top-down relationships, but not left-to-right relationships. Like logging. The code for logging is often spread horizontally across all object hierarchies, regardless of the core functionality of the object to which it is spread. This scattering of irrelevant code is called cross-cutting code, and in object-oriented design, it leads to a lot of code duplication and redundancy, which increases maintenance costs and is not conducive to module reuse.

AOP, on the other hand, uses a technique called “crosscutting” to rip open the insides of wrapped objects and encapsulate common behavior that affects multiple classes into a reusable module called “Aspect, “or section. The so-called “aspect”, in short, is to those who has nothing to do with the business, but the common public calls for business module logic encapsulated or responsibility, to facilitate cutting down on the amount of duplicate code system, and can reduce the coupling between modules, and help the operability and maintainability of the future, reduced maintenance costs.

Let’s take a look at AOP’s implementation strategy:

(1) Java SE dynamic proxy:

Using dynamic proxies, YOU can implement AOP by dynamically generating implementation objects at run time for one or more interfaces, and adding enhancement code to the generated objects to implement the methods of the interface. The disadvantage is that the proxy can only be used against the interface, and because dynamic proxy is through inverse

The overhead of reflection calls may sometimes be considered.

(2) Custom class loaders

Dynamic proxy and bytecode generation essentially require dynamic construction of proxy objects when enhancements are added to all objects of a class, i.e. the final enhanced object is generated by the AOP framework, not new by the developer. The solution is to implement custom class loaders that enhance a class as it is loaded. JBoss implements AOP functionality in this manner.

(3) Bytecode generation (CGLib dynamic proxy)

Dynamic bytecode generation is a technique that implements AOP by dynamically generating a subclass object of a specified class at run time and overriding specific methods therein. Its common tool is Cglib.

(4) Language extension

AspectJ is a common Java language extension that implements AOP in this way, with enhancements to constructor and attribute assignment operations.

(5) Code generation

Use tools to generate new code from existing code into which you can add any crosscutting code to implement AOP.

Usage scenarios for AOP

The types of AOP frameworks are as follows ↓↓↓↓ :

– > AspectJ

– > Spring AOP

– JBoss AOP

Write write write write write

There are many things you can do with AOP.

The most common is logging, such as system logging before and after method execution.

→ Again is the performance monitoring, such as before and after the method call record call time, method execution time is too long or timeout alarm.

→ Then there is the caching proxy, which caches the return value of a method and fetches it directly from the cache the next time the method is executed.

→ then is the software cracking, such as the use of AOP to modify the software of the validation class judgment logic and so on.

→ Then there is the workflow system, workflow system needs to execute the business code and process engine code mixed together, so we can use AOP to separate it, and dynamically hang the business.

→ Finally is the permission verification, method before the execution of the verification whether there is permission to execute the current method, no then throw no permission to execute the exception, captured by the business code.

Let’s take a look at how traditional coding differs from using AOP

Log processing

Description of Core concepts

Let’s describe some common AOP terms: Pointcut, Adivce, Join point, Introduction, Weaving, Aspect, etc.

Important concepts of AOP

Simple example (PS: It’s time to show real technology ~)

The annotation-based approach is much cleaner and more convenient than XML configuration. (PS: If you have read the previous article, you know that xiaobian likes to use annotations.)

@Aspect

public class SpringAOPDemo {

}

Configuration in applicationContext.xml.

To use aspects on the Aspect class, of course to use annotations you must first configure AOP in the XML file: AspectJ-AutoProxy.

The following is a Spring AOP.xml file template named ApplicationContext.xml, and the rest is extended on applicationContext.xml:

Talk about the principles of Spring AOP

The Spring AOP proxy is essentially an object that is dynamically generated by the Spring AOP framework and can be used as a target object. We fully proxy the target object. The Spring AOP proxy contains all the methods of the target object, But the methods in the Spring AOP proxy are different from those of the target object: Spring AOP methods add enhanced logical processing at specific pointcuts and call back the methods of the target object.

Methods of the proxy versus methods of the target object

Spring’s AOP proxies are completely generated and managed by Spring’s IoC container, and their dependencies are also managed by the IoC container. Thus, AN AOP proxy can directly target other Bean instances in the container, and this relationship can be provided by the dependency injection of the IoC container.

There are only three parts of AOP development that require programmer involvement:

Define common business components.

Define pointcuts, where a pointcut may crosscut multiple business components.

Define enhancements, which are processing actions woven into the AOP framework for common business components.

To clarify the relationship, start with a UML class diagram.

The main AOP component in Spring

AOP core Concepts

1. Crosscutting concerns

Which methods are intercepted, and how are they handled? These concerns are called crosscutting concerns

2. Aspect

A class is an abstraction of object features, and a section is an abstraction of crosscutting concerns

3, joinpoint (joinpoint)

The intercepted point. Since Spring only supports method type join points, join points in Spring refer to the method being intercepted. In fact, join points can also be fields or constructors

4. Pointcut

Definition of interception of join points

5. Advice

Notification refers to the code to be executed after intercepting the join point. Notification is divided into five categories: pre-notification, post-notification, exception, final notification, and surround notification

6. Target audience

The target object of the proxy

7. Weave

The process of applying a facet to a target object and resulting in the creation of a proxy object

8. Introduction

Imports can dynamically add methods or fields to a class at run time without modifying the code

Two examples:

Implement AOP with configuration files and annotations, respectively

XML configuration file:

TestAspect 1

2. AServiceImpl: Target object

3. BServiceImpl: indicates the target object

ApplicationContext: Spring configuration file

Second, Annotation

TestAnnotationAspect

ApplicationContext: Spring configuration file

If you can see here, you write a lot less code using annotations, so I recommend you to use annotations. Save time and effort.

Dynamic proxy implemented by the JDK

The JDK, the Java runtime environment, also provides dynamic proxies. Dynamic proxies in the JDK mainly involve two classes in the java.lang.Reflect package: Proxy and InvocationHandler. InvocationHandler is an interface that dynamically marshals crosscutting logic and business logic by implementing the interface that defines crosscutting logic and invokes the code of the target class through reflection.

Proxy uses InvocationHandler to dynamically create an instance of an interface that is used to generate a Proxy object for the target class.

Two dynamic proxy approaches

Spring implements AOP using the dynamic proxy mechanism by default, and of course uses CGlib’s mechanism when dynamic proxies are not available (proxy classes have no interfaces).

Spring provides two ways to generate Proxy objects: JDK Proxy and Cglib. AopProxyFactory determines which way to generate Proxy objects based on the configuration of the AdvisedSupport object. The default strategy is to use JDK dynamic proxy technology if the target class is an interface, otherwise use Cglib to generate the proxy. Spring will automatically choose to use that approach, so we don’t have to worry. Here’s an idea.

Dynamic proxy implemented by CGLib

CGLib dynamic proxy full name Code Generation Library, it is a powerful high-performance, high-quality Code Generation class Library, you can extend Java classes and implement Java interface at runtime, CGLib it encapsulates ASM, you can dynamically generate new classes at runtime. A comparison between CGLIB and JDK dynamic proxies: JDK proxies are limited to creating proxy instances for interfaces, whereas CGLIB can be used to create dynamic proxies for classes that do not define business methods through interfaces.

Summary: While the JDK creates proxy instances for interfaces, CGLIB can create proxy instances for classes.

Episode:

Today we are coming to the end of the introduction, are you still ignorant of SpringAOP? It doesn’t matter, you can leave a message to xiaobian, or private xiaobian. Xiaobian see will reply one by one yo. Hee hee ~

Other

Through the above analysis and introduction, friends whether there is a familiar feeling, as if. Seems to be. The function of interceptor and filter is similar. OK~ Then the question arises, how does AOP relate to interceptors and filters?

A review of interceptors and filters. The following image shows a friend’s test with TestFilter1 and TestFilter2 registered in web.xml. You then configure the BaseInterceptor and TestInterceptor in the Spring configuration file. The result is shown below. As you can see from the figure, both interceptors and filters crosscut business methods, seemingly in line with AOP thinking.

Interceptor: Intercepts.action urls that end in.action, blocking action access.

Filter: Intercepts the URL of the Web access.

Spring AOP interceptor: Intercepts access only to Spring managed beans (business layer Services)

Interceptors and filters