Spring's AOP is from simple to deep, and aop is from simple to deep

Source: Internet
Author: User

Spring's AOP is from simple to deep, and aop is from simple to deep

1. Functions of AOP

In OOP, the existence of code (cross-cutting code) That is scattered everywhere and irrelevant to the core functions of the object increases the difficulty of module reuse. AOP splits encapsulated objects, finds out the public behaviors that affect multiple objects, and encapsulates them into a reusable module, this module is named Aspect, which extracts and encapsulates the logic that is not related to the business but called by the business module together, reducing repeated code in the system, this reduces the coupling between modules and improves the maintainability of the system.

2. DI and IOC concepts

In the definition of dependency injection or control inversion, the caller is not responsible for creating the instance of the caller. The container in the Spring framework is responsible for this task. The caller determines the instance type through the configuration of the developer, after creation, inject the caller. Because the Spring container is in charge of the caller instance, and the instance is in charge of injecting the instance into the caller after creation, it is called dependency injection. The creation of the called instance is not created by the caller but by Spring. The control is transferred from the application code to the external container, and the control is reversed.

3. BeanFactory and ApplicationContext

ApplicationContext is a sub-interface of BeanFactory, also known as the application context. BeanFactory provides Spring configuration framework and basic functions, while ApplicationContext adds more enterprise-level functions (such as international support). Another important advantage is that after the ApplicationContext container is initialized, all the singleton beans in the container are also instantiated. That is to say, when you need to use singleton Bean, it can be used in the application without waiting, and other BeanFactory interface implementation classes, the construction will be delayed until the getBean () method is called. The initialization time of ApplicationContext will be a little longer. The getBean () method is called because the Bean has been constructed and the speed will be faster. Therefore, most systems use ApplicationContext, and BeanFactory is considered only when there are few resources.

4. Implementation Strategy of AOP

(1) Java SE dynamic Proxy:
Dynamic proxy can be used to dynamically generate implementation objects for one or more interfaces at runtime. When the generated objects implement interface methods, you can add enhanced code to implement AOP. The disadvantage is that you can only proxy the interface. In addition, because the dynamic proxy is implemented through reflection, you may have to consider the overhead of reflection calls.
(2) bytecode generation (CGLib dynamic proxy)
Dynamic bytecode generation technology is used to dynamically generate a subclass object of a specified class at runtime and overwrite specific methods. When overwriting methods, you can add enhanced code to implement AOP. The common tool is cglib.
(3) custom class loaders
When you need to add enhancements to all objects of the class, both dynamic proxy and bytecode generation need to dynamically construct the proxy object, that is, the final enhanced object is generated by the AOP framework, not new by developers. The solution is to implement a custom class loader and enhance a class when it is loaded. JBoss implements the AOP function in this way.
(4) Code Generation
Use tools to generate new code based on existing code. You can add any cross-cutting code to implement AOP.
(5) Language extensions
The constructor and attribute assignment operations can be enhanced. AspectJ is a common Java Language extension for AOP in this way.

 

Note: The aspect in AOP encapsulates the Advice and Pointcut. In the following example, only the enhancement is used, and the cut point is not added at the moment.

 

5. Programmatic Enhancement

Here, I first use the "programming" method, that is, the Bean object is defined without the Spring configuration file, and the new operation in the Code is not replaced.

(1) create an interface and implementation class

 

(2) Compile pre-enhancement and post-enhancement (here I merge the two enhancements to implement the two interfaces)

 

 

(3) JUnit for testing

 

 

(3) surround enhancement (when merging two interfaces, you can actually use one interface)

 

The org. aopalliance. intercept. MethodInterceptor interface must be implemented for the surround enhancement class. Note that this interface is not provided by Spring. It is written by the AOP consortium and Spring only borrows it.

 

And then add it to JUnit.

 

6. Declarative Enhancement

Now, configure the bean through the Spring configuration file. You do not need to configure <Bean id = "..." class = "..."/> in the configuration file.

(1) Spring configuration file (enhancement class is surround enhancement)

 

 

(2) Add the Component annotation to the corresponding implementation class and enhancement class.

 

 

(3) JUnit Test

Obtain the Bean object (actually a proxy) by id from the Context and call the proxy method.

 

Expected result

7. Introduction Advice (Introduction enhancement)

The above enhancement is only for method enhancement, that is, weaving. Class enhancement can be called introduction enhancement. For example, I don't want GreetingImpl to directly implement the Greeting interface, I have to implement his method. In this case, I can use Spring to introduce enhancements to help me achieve dynamic implementation.

(1) define a new interface Love

 

 

(2) define authorization and introduce enhancement classes

Define an authorization to introduce the enhancement class and implement the Love interface to enrich the GreetingImpl class functions. In this way, GreetingImpl Can skillfully use the methods in the Love interface instead of implement.

 

 

The configuration is as follows:

 

 

The proxyTargetClass attribute indicates whether the proxy target class is used. The default value is false, that is, the proxy interface. The configuration in the preceding example is that this attribute is not used, so JDK dynamic proxy is used, if it is true, CGLib dynamic proxy is used. Therefore, in the test method, GreetingImpl greetingImpl = (GreetingImpl) context. getBean ("beans. xml "), instead of Greeting greeting = (Greeting) context. getBean ("beans. xml "), because it is the proxy target class rather than the proxy interface.

 

(3) JUnit Test

 

 

 

Note: here the Love love = (Love) greetingImpl isForcibly convert the target class to the Love interface,ThisYesIntroduce the DelegatingIntroductionInterceptor feature --"Dynamic Interface implementation" Function. Therefore, the display () method can be called by the GreetingImpl object. You only need to forcibly convert the interface.

8. Aspect-Oriented Programming

(1) Notification (enhancement) Advice

The notification defines what the aspect is and when to use it. Should it be applied before a method is called? After? Or throw an exception? And so on.

(2) Join point

A connection point is a point that can insert a plane surface during application execution. This point can be used when a method is called, an exception is thrown, or even a field is modified. The aspect code can use these points to insert them into the normal process of the application and add new behaviors.

(3) Pointcut

The Slice helps narrow the range of the connection points notified by the slice. If a notification defines "what" and "when", the cut point defines "where", and the cut point matches one or more connection points to be woven into the notification, generally, regular expressions are used to define matched class and method names to specify these tangent points.

(4) Aspect

A cut section is a combination of notifications and cut points. The notification and cut points define all the content of the Cut-plane-what it is and where it completes its functionality.

(5) Introduce Introduction

The introduction allows us to add new methods or attributes to existing classes so that they have new behaviors and States without having to modify these existing classes.

(6) woven into Weaving

In the past, I often confused the concepts of organization and introduction. In this way, I can identify "Introduction". I regard it as a definition, that is, a term, as for "Weaving", I regard it as an action, a verb, that is, the aspect is woven into the target object at the specified connection point.

9. Summary

The notification contains the cross-cutting behavior that needs to be used for multiple application objects. The connection point is all points that can be notified during program execution; the switch point defines the specific location of the notification to be applied (in which connection points ). The key concept is to define the connection points to be notified (enhanced ). Creating a cut point to define the join points woven by the cut plane is the basic function of the AOP framework.

In addition, Spring is based on dynamic proxy, so Spring only supports method connection points. In addition to method cut points, AspectJ and JBoss also provide field and constructor access points. If you need to intercept connection points other than methods, you can use AspectJ to supplement the SpringAOP function.

10. SpringAOP face-cutting class based on regular expressions

Here, springAOP's face-cutting class RegexpMethodPointcutAdvisor is used to configure the face layer, and two methods starting with "good" are added to the GreetingImpl class. The following is to intercept two new methods, sayHello () is not blocked.

 

 

 

The above InterceptorNames attribute is no longer an enhancement, but a defined aspect greetingAdvisor. In the aspect, a cut point is defined using a regular expression, that is, the method starting with good in the GreetingImpl class is intercepted.

JUnit test:

11. Automatic AOP proxy

(1) The Spring framework automatically generates a proxy.

 

 

 

Attribute optimize indicates whether to optimize the proxy generation policy. true indicates that if the target class has an interface, the proxy interface (JDK dynamic proxy) is used. If not, the proxy class (CGLib dynamic proxy) is used ), in this way, the proxyTargetClass attribute of the forced proxy class can be replaced.

 

 

 

In this case, because it is an automatic proxy, the value in getBean () is no longer the original proxy id (greetingProxy), but the id (GreetingImpl) of the target class greetingImpl, which is also a proxy object.

 

 

(2) spring generates automatic proxy Based on Bean name

The beanNames attribute indicates that only the bean id suffix is "Impl" to generate a proxy.

12. AspectJ execution expression Blocking

Defines a face-cutting class to enhance the surround function. @ Aspect annotation does not require a class to implement the interface. @ Around annotation is an AspectJ cut-point expression. The object of the ProceedingJoinPoint parameter is the connection point. The method name and parameter can be obtained for this connection point.

This two-line configuration saves a lot of time for configuring proxy and cropping. If proxy-target-class is true, it indicates the proxy target class.

 

The previous cut-point expression defines all methods in the interception class, so each method is enhanced. At the same time, the greetingImpl proxy object obtained in ApplicationContext can be transformed into its own static implementation interface Greeting or implementation class GreetingImpl. The default value of the proxy-target-class attribute is false, indicating that only the proxy interface is used. That is to say, the proxy can only be converted to Greeting, not GreetingImpl.

Implementation class GreetingImpl:

 

 

P.s what will happen if we change the vertex in the face-cutting class from the original implementation class GreetingImpl to the interface Greeting?

 

Changed:

 

 

The result shows that the methods for implementing interfaces in the implementation class are enhanced, but the good method created by myself is not enhanced. This is because all the methods in the Greeting interface are enhanced because the cut points are set, therefore, the methods implemented in this interface are enhanced.

 

 

 

13. AspectJ @ DeclareParents annotation (Introduction enhancement)

Define a partition class AroundAspect: The value Attribute specifies the type of bean to introduce this interface. The defaultImpl attribute specifies the class to be implemented for the introduced function. The attribute marked by the @ DeclareParents annotation specifies the interface to be introduced.

 

LoveImpl implementation class: introduce this implementation class into the target class GreetingImpl, you can use the display method.

JUnit test:

 

Note: The greetingImpl object obtained in ApplicationContext is a proxy object. It can be transformed to its own static implementation interface Greeting, or its own dynamic implementation interface Love. You can switch between them at will. The introduction enhancements of AspectJ keep up with the introduction enhancements of SpringAOP which can only be aimed at implementation classes, but also interface programming. There are two ways to achieve this:

 

Console output:

 

The enhancements introduced by SpringAOP are only applicable to implementation classes:

 

 

14. Spring AspectJ automatic proxy

Spring's AspectJ automatic proxy only uses @ AspectJ as the guide for creating a plane, and the plane is still based on the agent. In essence, it is still a proxy-based aspect of Spring. This means that although the @ AspectJ annotation is used, we are still limited to calling proxy methods. When Spring finds that a bean uses the @ Aspect annotation, Spring will create a proxy and then delegate the call to the bean to the proxy or the introduced implementation, this depends on whether the called method belongs to the bean to be proxy or the introduced interface.

15. Declare the section in XML

In Spring, annotations and automatic proxies provide a convenient way to create a plane, but the annotation-oriented plane has a obvious disadvantage: You must be able to add annotations to the notification class, for this purpose, the source code must be available. If you do not have the source code, or you do not want to put the AspectJ annotation in your code, Spring provides another method to declare the aspect in the Spring XML configuration file.

Remove the related annotations @ Component, @ Aspect, and @ Around of the previous implementation class GreetingImpl and cut class AroundAspect. Edit XML:

 

We found that the original two configurations can be deleted, but note that no explicit configuration <aop: aspectj-autoproxy/> does not mean that automatic proxy is not used, the default attribute of this configuration is "false", indicating only proxy interfaces (JDK dynamic proxy). If you only want proxy interfaces, you do not need to explicitly write them out.

If you want to use CGLib dynamic proxy, add

In this case, you can proxy the target class:

 

 

16. END

This article is a collection of some of my knowledge and examples of Spring practice and AOP. I hope you can implement it together. If you think it is good, please give me a thumbs up or follow me up and share more knowledge in the future!

 

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.