Spring3.x tutorial (2) Spring AOP

Source: Internet
Author: User

Spring3.x tutorial (2) Spring AOP
I. Introduction to Spring AOPIn fact, development is constantly refactoring, abstracting and repeating code, and then encapsulating it. From the most primitive Modular programming to object-oriented programming, code encapsulation becomes more and more neat and clear, but there are still repeated code, which are almost all system logic code unrelated to the business logic. For example, Database Transaction Processing exists in the insert, update, and delete methods of data operations, and the logging logic exists in important business logic methods. Every application system has such system-level repeated logic code, and we do not have a better way to abstract and manage the code. However, the emergence of AOP makes up for this defect. AOP can intercept the original business without changing the original business logic code and process repeated system logic. Like the Ioc container, AOP is also one of the core modules of Spring. AOP is short for Aspect-Oriented Programming. It is usually called Aspect-Oriented Programming. We have learned OOP and object-oriented programming. AOP is not an alternative to OOP, but a useful supplement to OOP. It should be pointed out that the application scenarios of AOP are limited. It is generally only suitable for application scenarios with cross-cutting logic, such as performance monitoring, access control, transaction management, and logging, it is not suitable for processing specific business logic. Distributed Processing of business logic will lead to logic confusion and increase maintenance costs.Ii. How to Use Spring AOPThe following describes how to use Spring AOP to intercept user operation class UserDao. 1. Create a Java project, add Spring AOP dependency support aopalliance-1.0.jar commons-logging-1.1.1.jar spring-aop-3.2.0.RELEASE.jar spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar 2. Add User and UserDao class User class:

public class User {    private Integer id;    private String name;}
UserDao class:
public class UserDao {    public void save(User user){        System.out.println("save user....");    }        public void delete(int id){        System.out.println("delete user....");    }        public void update(User user) {        System.out.println("update user ....");    }        public User query(String name) {        System.out.println("getUser ....");        return new User();    }}
3. Add a pre-notification for AOP interception and processing:
Public class UserBeforeAdvice implements MethodBeforeAdvice {public void before (Method method, Object [] args, Object target) {System. out. println ("Call method:" + method. getName () + "() Interception processing ");}}
Post-Notification of AOP:
Public class UserAfterAdvice implements AfterReturningAdvice {public void afterReturning (Object returnValue, Method method, Object [] args, Object target) {System. out. println ("method:" + method. getName () + "() Return and intercept ");}}
AOP surround notification:
Public class UserAroundAdvice implements MethodInterceptor {public Object invoke (MethodInvocation invocation) throws Throwable {System. out. println ("Call method:" + invocation. getMethod (). getName () + "() before interception"); Object o = invocation. proceed (); System. out. println ("Call method:" + invocation. getMethod (). getName () + "() after interception"); return o ;}}
4. Add the Spring configuration file applicationContext. xml.
 
     
      
       
        
         
       
        
        
         
          userAroundAdvice
         
         
        
        
      
     
    
   
  
 
5. Test AOP
public static void main(String[] args) {    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");    UserDao userDao = context.getBean("userDao", UserDao.class);    userDao.save(new User());}
Output result:
Call method: intercept before save (). save user... Call method: save (). Intercept.
Let's look at the example. 1. First, the original business logic code remains unchanged and no longer cares about repeated system logic Code 2. Write the AOP aspect processing logic to abstract the repeated code in the original business logic and encapsulate it into the aspect code, as shown in the preceding example, three Advice notifications encapsulate different system processing logic. Pre-notification: implement the MethodBeforeAdvice interface. Call this interface before calling the business method. Post-Notification: implement the AfterReturningAdvice interface and call this interface after the business method returns, in this interface, you can view the returned value (but cannot modify the returned value) and notify the user that the MethodInterceptor interface is implemented. In this interface, invocation is implemented. proceed (); this method will call the method of the real object
3. Use the Spring configuration file to assemble the business logic and the AOP aspect logic. Set the AOP proxy Bean type to org. springframework. aop. framework. proxyFactoryBean must set the proxy target (target attribute setting) and the notification type (interceptorNames attribute setting). The proxy target is not required to implement the interface. When the proxy is used as a POJO, all methods of the target will be intercepted. Iii. Implementation Principles of AOPSpring AOP is implemented based on Java reflection and dynamic proxy. Before explaining the dynamic proxy, let's review the proxy mode. The proxy mode provides a proxy for an object to operate on it through the proxy. Generally, the real object and the proxy object must implement the same interface and save the reference of the real object in the proxy object to control the operation of the real object. We use the shift leader as the representative teacher to sign in to demonstrate the Agency mode. Create sign-In interface:
public interface SignInterface {    public Object sign(String nameList);}
Create a real object, Teacher class:
public   class  Teacher  implements  SignInterface {     public  Object sign(String nameList) {        System. out .println( "Teacher sign..." );         return   new  Object();    }}
Create a proxy object, Leader class:
public class Leader implements SignInterface {    private Teacher teacher;    public Object sign(String nameList) {        if (teacher == null) {            teacher = new Teacher();        }        Object o = teacher.sign(nameList);        return o;    }}
Test agent:
public static void main(String[] args) {    SignInterface s = new Leader();    s.sign("names");}
The above is an example of the proxy mode. The proxy class has been created during compilation, and the dynamic proxy creates the proxy class dynamically at runtime to implement the proxy mode. The following code:
Public class ProxyObject implements InvocationHandler {private Object proxy_obj; ProxyObject (Object obj) {this. proxy_obj = obj;} public static Object getProxy (Object obj) {Class cls = obj. getClass (); // return the Proxy object return Proxy through the newProxyInstance method of the Proxy class. newProxyInstance (cls. getClassLoader (), cls. getInterfaces (), new ProxyObject (obj);}/*** InvocationHandler interface invoke */public Object invoke (Ob Ject proxy, Method method, Object [] args) throws Throwable {System. out. println ("Call method:" + method + "() Interception and processing"); if (args! = Null) {System. out. println ("methods include" + args. length + "Parameters"); for (int I = 0; I <args. length; I ++) {System. out. println (args [I]) ;}// uses the reflection mechanism to dynamically call the real Object method Object o = method. invoke (proxy_obj, args); System. out. println ("Call method:" + method + "() after interception"); return o;} // test code public static void main (String agr []) {SignInterface si = (SignInterface) getProxy (new Teacher (); si. sign ("names ");}}
The above is the dynamic Proxy implemented using the JDK Proxy, but the dynamic Proxy Implementation of JDK only supports the dynamic Proxy implementation for the interface. The implementation of Spring AOP is also a dynamic Proxy by default. However, Spring AOP supports the implementation of CGLib Proxy and can dynamically Proxy POJO to implement AOP interception. Let's take a look at a simple AOP interception implemented by CGLib to create a business POJO:
public class CGLibTeacher {    public Object sign(String nameList) {        System.out.println("Teacher sign...");        return new Object();    }}
Create AOP interception:
public class CGLibAop implements MethodInterceptor {        public Object intercept(Object arg0, Method arg1, Object[] arg2,                   MethodProxy arg3) throws Throwable {               System.out.println("before...");            Object o = arg3.invokeSuper(arg0, arg2);            System.out.println("after...");            return o;        }   }
CGLib proxy object creation and testing:
Public class CGLibProxy {public static CGLibTeacher create (CGLibAop aop) {Enhancer en = new Enhancer (); // proxy en. setSuperclass (CGLibTeacher. class); en. setCallback (aop); // generate proxy instance return (CGLibTeacher) en. create ();} public static void main (String [] args) {CGLibTeacher t = CGLibProxy. create (new CGLibAop (); t. sign ("names ");}}
From the creation of the CGLib proxy object, we can see that the proxy object needs to set the proxy object and implement the AOP interception, which is very similar to the implementation of Spring AOP.

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.