Spring Framework AOP Detailed

Source: Internet
Author: User
Tags aop

I. Preface

In previous projects, very little attention to the specific implementation and theory of spring AOP, just a simple understanding of what is AOP specific how to use, see a blog post is also good, reproduced to learn, Bowen address: http://www.cnblogs.com/xrq730/p /4919025.html

Aop

AOP (Aspect oriented programming), which is aspect-oriented programming, can be said to complement and refine OOP (object oriented programming, OO programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. However, OOP allows developers to define vertical relationships, but it is not appropriate to define landscape-like relationships, such as logging capabilities. The log code tends to spread horizontally across all object hierarchies, and it has nothing to do with the core functionality of the object it corresponds to, such as the persistence of other types of code, such as security, exception handling, and transparency, the extraneous code scattered around is called crosscutting (cross Cutting), in the OOP design, It leads to a lot of duplication of code and is not conducive to the reuse of individual modules.

AOP technology, 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, named "Aspect", or tangent. The so-called "cut-off", simply said to be those unrelated to the business, but for the business module calls together the logic or responsibility to encapsulate, easy to reduce the system duplication of code, reduce the coupling between modules, and conducive to future operability and maintainability.

Using "crosscutting" techniques, AOP divides software systems into two parts: core concerns and crosscutting concerns . The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in many of the core concerns and are similar everywhere, such as authority authentication, logging, and things. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns.

AOP Core Concepts

1. Cross-cutting concerns

What methods to intercept and how to deal with them, these concerns are called crosscutting concerns.

2. Slice (aspect)

A class is an abstraction of an object's characteristics, and a facet is an abstraction of a crosscutting concern.

3, Connection point (Joinpoint)

The point that is intercepted, because spring only supports connection points of the method type, so the connection point in spring refers to the method being intercepted, in fact the connection point can also be a field or a constructor

4. Entry point (pointcut)

Definition of interception of connection points

5. Notice (advice)

The so-called notification refers to the interception to the connection point after the code to execute, the notification is divided into pre-, post-, exception, final, surround notification five categories

6. Target Object

Target object for the agent

7. Weave in (weave)

The process of applying a slice to the target object and causing the proxy object to be created

8. Introduction (Introduction)

Without modifying the code, the introduction can dynamically add some methods or fields to the class at run time

Spring's support for AOP

The AOP agent in spring is generated and managed by the spring IOC container, and its dependencies are managed by the IOC container . Therefore, the AOP proxy can use the other bean instances in the container directly as a target, a relationship that can be provided by the dependency injection of the IOC container. The rules for creating a proxy for spring are:

1. Use the Java Dynamic Agent to create an AOP proxy by default , so that you can create proxies for any interface instances

2, when the class that needs the proxy is not the proxy interface, spring switches to use the Cglib proxy , or it can force the use of Cglib

AOP programming is actually a simple thing, and throughout AOP programming, programmers only need to participate in three parts:

1. Define Common business components

2, define pointcuts, a pointcut may cross-cutting multiple business components

3, the definition of enhanced processing, enhanced processing is the AOP framework for ordinary business components to weave the processing action

So the key to AOP programming is defining pointcuts and defining enhanced processing, and once the appropriate pointcuts and enhancements are defined, the AOP framework automatically generates an AOP proxy, the method of the Proxy object = The method of enhancing processing + the Proxied object .

The following is a spring AOP. xml file template, named Aop.xml, after which the content is extended on Aop.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"    Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"    xmlns:aop= "Http://www.springframework.org/schema/aop "    xmlns:tx=" http://www.springframework.org/schema/tx "    xsi:schemalocation=" http// Www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd        HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd " >            </beans>

Simple implementation of AOP based on spring

Note, before you explain, that using spring AOP, it is not enough to run the code successfully, only the jar package provided by spring to the developer, please download two additional jar packages on the Internet:

1, Aopalliance.jar

2, Aspectjweaver.jar

Start with the XML implementation of Spring AOP, defining an interface first:

public interface helloworld{    void Printhelloworld ();    void Doprint ();}

Define two interface implementation classes:

public class HELLOWORLDIMPL1 implements helloworld{public    void Printhelloworld ()    {        System.out.println (" Enter Helloworldimpl1.printhelloworld () ");        public void Doprint ()    {        System.out.println ("Enter helloworldimpl1.doprint ()");        return;}    }
public class HELLOWORLDIMPL2 implements helloworld{public    void Printhelloworld ()    {        System.out.println ("Enter Helloworldimpl2.printhelloworld ()");    }        public void Doprint ()    {        System.out.println ("Enter helloworldimpl2.doprint ()");        return;}    }

Crosscutting concerns, here is the print time:

public class timehandler{public    void Printtime ()    {        System.out.println ("currenttime =" + System.currenttimemillis ());}    }

With these three classes you can implement a simple spring AOP, and look at the configuration of the Aop.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-4.2.xsd "> <bean id=" helloWorldImpl1 "class=" COM.XRQ.AOP . HelloWorldImpl1 "/> <bean id=" helloWorldImpl2 "class=" com.xrq.aop.HelloWorldImpl2 "/> <bean id=" Timehandler "class=" Com.xrq.aop.TimeHandler "/> <aop:config> <aop:aspect id=" Time "R ef= "Timehandler" > <aop:pointcut id= "addallmethod" expression= "Execution (* com.xrq.aop.helloworld.* (... )) "/> <aop:bEfore method= "Printtime" pointcut-ref= "Addallmethod"/> <aop:after method= "Printtime" pointcut-ref= "a Ddallmethod "/> </aop:aspect> </aop:config></beans>

Write a main function call:

public static void Main (string[] args) {    ApplicationContext ctx =             new Classpathxmlapplicationcontext ("Aop.xml" );            HelloWorld hw1 = (HelloWorld) ctx.getbean ("HelloWorldImpl1");    HelloWorld hw2 = (HelloWorld) ctx.getbean ("HelloWorldImpl2");    Hw1.printhelloworld ();    System.out.println ();    Hw1.doprint ();        System.out.println ();    Hw2.printhelloworld ();    System.out.println ();    Hw2.doprint ();}

The result of the operation is:

CurrentTime = 1446129611993Enter Helloworldimpl1.printhelloworld () currenttime = 1446129611993CurrentTime = 1446129611994Enter helloworldimpl1.doprint () currenttime = 1446129611994CurrentTime = 1446129611994Enter Helloworldimpl2.printhelloworld () currenttime = 1446129611994CurrentTime = 1446129611994Enter Helloworldimpl2.doprint () CurrentTime = 1446129611994

See all the methods of the two implementation classes to the HelloWorld interface with the agent, the agent content is the printing time

Spring-based AOP uses other details

1. Add a crosscutting concern, print logs, Java classes are:

public class loghandler{public    void Logbefore ()    {        System.out.println ("Log before Method");        public void Logafter ()    {        System.out.println (' Log after Method ');}    }
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-4.2.xsd "> <bean id=" helloWorldImpl1 "class=" COM.XRQ.AOP . HelloWorldImpl1 "/> <bean id=" helloWorldImpl2 "class=" com.xrq.aop.HelloWorldImpl2 "/> <bean id="                Timehandler "class=" Com.xrq.aop.TimeHandler "/> <bean id=" Loghandler "class=" Com.xrq.aop.LogHandler "/> <aop:config> <aop:aspect id= "Time" ref= "Timehandler" order= "1" > &LT;AOP :p ointcut id= "Addtime" expression="Execution (* com.xrq.aop.helloworld.* (..))"/> <aop:before method= "printtime" pointcut-ref= "AddTime"            /> <aop:after method= "printtime" pointcut-ref= "Addtime"/> </aop:aspect> <aop:aspect id= "Log" ref= "Loghandler" order= "2" > <aop:pointcut id= "printlog" expression= "execut                Ion (* com.xrq.aop.helloworld.* (..)) "/> <aop:before method=" Logbefore "pointcut-ref=" Printlog "/> <aop:after method= "Logafter" pointcut-ref= "Printlog"/> </aop:aspect> </ao P:config></beans>

The test class does not change and the result is printed as:

CurrentTime = 1446130273734Log before Methodenter helloworldimpl1.printhelloworld () Log After methodcurrenttime = 1446130273735CurrentTime = 1446130273736Log before Methodenter helloworldimpl1.doprint () Log After methodcurrenttime = 1446130273736CurrentTime = 1446130273736Log before Methodenter helloworldimpl2.printhelloworld () Log after Methodcurrenttime = 1446130273736CurrentTime = 1446130273737Log before Methodenter helloworldimpl2.doprint () Log after Methodcurrenttime = 1446130273737

There are two ways to get Loghandler to use before Timehandler:

(1) There is an order attribute in the aspect, and the number of the order attribute is the order of the crosscutting concern.

(2) Define Loghandler in front of Timehandler, spring defaults to aspect as the order of weaving

2. I just want to weave some methods into the interface

Just modify Pointcut's expression:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-4.2.xsd "> <bean id=" helloWorldImpl1 "class=" COM.XRQ.AOP . HelloWorldImpl1 "/> <bean id=" helloWorldImpl2 "class=" com.xrq.aop.HelloWorldImpl2 "/> <bean id="                Timehandler "class=" Com.xrq.aop.TimeHandler "/> <bean id=" Loghandler "class=" Com.xrq.aop.LogHandler "/> <aop:config> <aop:aspect id= "Time" ref= "Timehandler" order= "1" > &LT;AOP :p ointcut id= "Addtime" expression="Execution (* com.xrq.aop.helloworld.print* (..))"/> <aop:before method= "printtime" pointcut-ref= "AddT            IME "/> <aop:after method=" printtime "pointcut-ref=" Addtime "/> </aop:aspect> <aop:aspect id= "Log" ref= "Loghandler" order= "2" > <aop:pointcut id= "printlog" expression= "E  Xecution (* com.xrq.aop.helloworld.do* (..)) "/> <aop:before method=" Logbefore "pointcut-ref=" PrintLog "        /> <aop:after method= "Logafter" pointcut-ref= "Printlog"/> </aop:aspect> </aop:config></beans>

means that the Timehandler will only weave into the HelloWorld interface print beginning method, Loghandler will only weave into the HelloWorld interface do Start method

3, forcing the use of cglib generation agent

As I said before, Spring uses dynamic proxy or Cglib build agent is regular, the higher version of spring will automatically choose whether to use dynamic agent or Cglib to generate proxy content, of course, we can also force the use of cglib generation agent, that is <aop:config > There is a "proxy-target-class" attribute, and if this property value is set to True, then the class-based proxy will work if Proxy-target-class is set to False or if the attribute is omitted, Then the interface-based proxy will work

Spring Framework AOP Detailed

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.