SpringAop details,

Source: Internet
Author: User

SpringAop details,

Recently I learned SpringAop and found some information on the Internet. This link is the original link http://www.cnblogs.com/xrq730/p/4919025.html.

AOP

AOP (Aspect Oriented Programming) is a supplement and improvement of Object-Oriented Programming (OOP. OOP introduces concepts such as encapsulation, inheritance, and Polymorphism to establish an object hierarchy for simulating a set of public behaviors. However, OOP allows developers to define vertical relationships, but it is not suitable for defining horizontal relationships, such as the log function. Log Code is usually distributed horizontally across all object layers, and its core functions are irrelevant to other types of code, this is also true for security, exception handling, and transparent continuity. Unrelated code distributed everywhere is called cross-cutting. in OOP design, it leads to a lot of code duplication, and is not conducive to the reuse of each module.

The AOP technology is the opposite. It uses a technology called "cross-cutting" to segment the encapsulated object, encapsulate the public behaviors that affect multiple classes into a reusable module and name it "Aspect", that is, the Aspect. The so-called "aspect" is simply encapsulated by the logic or responsibilities that are not related to the business, but are called by the business module, so as to reduce the repeated code of the system and reduce the coupling between modules, it is also conducive to future operability and maintainability.

Using the "cross-cutting" technology, AOP divides the software system into two parts:Core concernsAndCross-concern. The main process of business processing is the core focus, and the part that has little to do with it is the cross-cutting focus. One feature of cross-cutting concerns is that they often occur in multiple aspects of the core concerns, and are similar everywhere, such as permission authentication, logs, and transactions. The function of AOP is to separate the various concerns in the system from the core concerns and the cross-cutting concerns.

 

Core AOP concepts

1. Cross-cutting concerns

Methods to intercept and how to handle the interception are called cross-cutting concerns.

2. aspect)

Class is the abstraction of object features, and the aspect is the abstraction of cross-cutting concerns.

3. Connection Point (joinpoint)

The intercepted point. Because Spring only supports connection points of the method type, the connection point in Spring refers to the method to be intercepted. In fact, the connection point can also be a field or constructor.

4. pointcut)

Definition of interception of connection points

5. advice)

The notification refers to the code to be executed after the interception to the connection point. The notification is divided into five categories: front, rear, exception, final, and surround notification.

6. Target object

Proxy target object

7. weave)

Process of applying a cut surface to the target object and causing the creation of the proxy object

8. introduction)

Without modifying the code, you canRuntimeDynamically add some methods or fields to the class

 

Spring's support for AOP

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

1,By default, Java Dynamic proxy is used to create an AOP proxy.In this way, you can create a proxy for any interface instance.

2,When the class to be proxy is not a proxy interface, Spring will switch to use CGLIB proxy, You can also use CGLIB forcibly

AOP programming is actually very simple. Throughout AOP programming, programmers only need to participate in three parts:

1. Define Common Business Components

2. Define an entry point. A single entry point may cross multiple business components.

3. Define the enhancement processing. The enhancement processing is the processing action that is woven into common business components in the AOP framework.

Therefore, the key to AOP programming is to define the entry point and definition enhancement processing. Once an appropriate entry point and enhancement processing are defined, the AOP framework will automatically generate the AOP proxy, namely:Proxy object method = enhanced processing + proxy object.

The following is a Spring AOP. xml file template named aop. xml. All subsequent content is extended on aop. xml:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:aop="http://www.springframework.org/schema/aop" 5     xmlns:tx="http://www.springframework.org/schema/tx" 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8         http://www.springframework.org/schema/aop 9         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">10             11 </beans>

Simple Spring-based AOP implementation

Note: Before explaining this, it is not enough to use only the jar packages provided by Spring to developers to successfully run the code. Please download two additional jar packages online:

1. aopalliance. jar

2. aspectjweaver. jar

Start with the XML Implementation Method of Spring AOP. First define an interface:

1 public interface HelloWorld2 {3     void printHelloWorld();4     void doPrint();5 }

Define two interface implementation classes:

 1 public class HelloWorldImpl1 implements HelloWorld 2 { 3     public void printHelloWorld() 4     { 5         System.out.println("Enter HelloWorldImpl1.printHelloWorld()"); 6     } 7      8     public void doPrint() 9     {10         System.out.println("Enter HelloWorldImpl1.doPrint()");11         return ;12     }13 }
 1 public class HelloWorldImpl2 implements HelloWorld 2 { 3     public void printHelloWorld() 4     { 5         System.out.println("Enter HelloWorldImpl2.printHelloWorld()"); 6     } 7      8     public void doPrint() 9     {10         System.out.println("Enter HelloWorldImpl2.doPrint()");11         return ;12     }13 }

Cross-cutting concern. Here is the printing time:

1 public class TimeHandler2 {3     public void printTime()4     {5         System.out.println("CurrentTime = " + System.currentTimeMillis());6     }7 }

With these three classes, you can implement a simple Spring AOP. Let's take a look at the configuration of aop. xml.

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:aop="http://www.springframework.org/schema/aop" 5     xmlns:tx="http://www.springframework.org/schema/tx" 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8         http://www.springframework.org/schema/aop 9         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">10         11         <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />12         <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />13         <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />14         15         <aop:config>16             <aop:aspect id="time" ref="timeHandler">17                 <aop:pointcut id="addAllMethod" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />18                 <aop:before method="printTime" pointcut-ref="addAllMethod" />19                 <aop:after method="printTime" pointcut-ref="addAllMethod" />20             </aop:aspect>21         </aop:config>22 </beans>

Write a main function and call it:

 1 public static void main(String[] args) 2 { 3     ApplicationContext ctx =  4             new ClassPathXmlApplicationContext("aop.xml"); 5          6     HelloWorld hw1 = (HelloWorld)ctx.getBean("helloWorldImpl1"); 7     HelloWorld hw2 = (HelloWorld)ctx.getBean("helloWorldImpl2"); 8     hw1.printHelloWorld(); 9     System.out.println();10     hw1.doPrint();11     12     System.out.println();13     hw2.printHelloWorld();14     System.out.println();15     hw2.doPrint();16 }

The running result is:

CurrentTime = 1446129611993Enter HelloWorldImpl1.printHelloWorld()CurrentTime = 1446129611993CurrentTime = 1446129611994Enter HelloWorldImpl1.doPrint()CurrentTime = 1446129611994CurrentTime = 1446129611994Enter HelloWorldImpl2.printHelloWorld()CurrentTime = 1446129611994CurrentTime = 1446129611994Enter HelloWorldImpl2.doPrint()CurrentTime = 1446129611994

The proxy is added to all the methods of the two implementation classes of the HelloWorld interface. The proxy content is the printing time.

Other details about Spring-based AOP

1. Add a crosstab concern and print the log. The Java class is:

 1 public class LogHandler 2 { 3     public void LogBefore() 4     { 5         System.out.println("Log before method"); 6     } 7      8     public void LogAfter() 9     {10         System.out.println("Log after method");11     }12 }

Configure aop. xml as follows:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:aop="http://www.springframework.org/schema/aop" 5     xmlns:tx="http://www.springframework.org/schema/tx" 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8         http://www.springframework.org/schema/aop 9         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">10         11         <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />12         <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />13         <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />14         <bean id="logHandler" class="com.xrq.aop.LogHandler" />15         16         <aop:config>17             <aop:aspect id="time" ref="timeHandler" order="1">18                 <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />19                 <aop:before method="printTime" pointcut-ref="addTime" />20                 <aop:after method="printTime" pointcut-ref="addTime" />21             </aop:aspect>22             <aop:aspect id="log" ref="logHandler" order="2">23                 <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />24                 <aop:before method="LogBefore" pointcut-ref="printLog" />25                 <aop:after method="LogAfter" pointcut-ref="printLog" />26             </aop:aspect>27         </aop:config>28 </beans>

The test class remains unchanged and the printed result is:

 1 CurrentTime = 1446130273734 2 Log before method 3 Enter HelloWorldImpl1.printHelloWorld() 4 Log after method 5 CurrentTime = 1446130273735 6  7 CurrentTime = 1446130273736 8 Log before method 9 Enter HelloWorldImpl1.doPrint()10 Log after method11 CurrentTime = 144613027373612 13 CurrentTime = 144613027373614 Log before method15 Enter HelloWorldImpl2.printHelloWorld()16 Log after method17 CurrentTime = 144613027373618 19 CurrentTime = 144613027373720 Log before method21 Enter HelloWorldImpl2.doPrint()22 Log after method23 CurrentTime = 1446130273737

There are two ways to use logHandler before timeHandler:

(1) There is an order attribute in aspect, and the number of the order attribute is the sequence of the Cross-concern. The larger the number, the closer the execution is to the back, the opposite of the Post-notification.

(2) define logHandler before timeHandler. Spring uses the defined order of aspect as the weaving order by default.

2. I only want to weave some methods in the interface.

Modify the expression of pointcut:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:aop="http://www.springframework.org/schema/aop" 5     xmlns:tx="http://www.springframework.org/schema/tx" 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8         http://www.springframework.org/schema/aop 9         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">10         11         <bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />12         <bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />13         <bean id="timeHandler" class="com.xrq.aop.TimeHandler" />14         <bean id="logHandler" class="com.xrq.aop.LogHandler" />15         16         <aop:config>17             <aop:aspect id="time" ref="timeHandler" order="1">18                 <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.print*(..))" />19                 <aop:before method="printTime" pointcut-ref="addTime" />20                 <aop:after method="printTime" pointcut-ref="addTime" />21             </aop:aspect>22             <aop:aspect id="log" ref="logHandler" order="2">23                 <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.do*(..))" />24                 <aop:before method="LogBefore" pointcut-ref="printLog" />25                 <aop:after method="LogAfter" pointcut-ref="printLog" />26             </aop:aspect>27         </aop:config>28 </beans>

Indicates that timeHandler will only weave the method starting with the HelloWorld interface print, and logHandler will only weave the method starting with the HelloWorld interface do

3. Use CGLIB to generate a proxy

As mentioned earlier, Spring has rules for using dynamic proxies or CGLIB to generate proxies. In later versions, Spring automatically selects whether to use dynamic proxies or CGLIB to generate proxy content, of course, we can also force CGLIB to generate a proxy, that is, <aop: config> contains a "proxy-target-class" attribute. If this attribute value is set to true, the class-based proxy will take effect. If the proxy-target-class is set to false or this attribute is omitted, the interface-based proxy will take effect.

Related 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.