Spring AOP Small Note

Source: Internet
Author: User
Tags aop

I. Overview

In the usual development process, the order in which we call is usually Controller->service-dao, where the service contains too much business logic, and it is also constantly called DAO to implement its own business logic, which often leads to long-time business. Before AOP occurs, the usual way is to start writing a starttime in the function, ending with a endtime to see how time it takes to execute the function, too much use of such a method can lead to too much coupling of the code, which is not conducive to management, so AOP (face tangent) appears. AOP focuses on landscape, while OOP is portrait-oriented.

Spring has been using @aspectj annotations since version 2.0 to define a facet very easily. @AspectJ annotations Use the ASPECTJ pointcut expression syntax for pointcut definitions, which can be defined by pointcuts using advanced features such as pointcut functions, operators, and wildcard characters, with a strong connection point description capability.

1.1 Features

AOP (Aspect oriented programming) is a technique for cutting-plane programming, which implements the horizontal multi-module unified control of program functions through precompilation and run-time dynamic agent. AOP is a complement to OOP and an important part of the spring framework. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development. AOP can be divided into static weaving and dynamic weaving, static weaving is the need to weave the content into the target module before compiling, so the cost is very high. Dynamic weaving does not require changing the target module. The spring framework implements AOP, and using annotations to configure AOP is more convenient and intuitive than using XML configuration.

1.2 AOP Overview

Aspect: A module is used to focus on facets of multiple classes. In Java EE applications, transactions are a typical example of AOP.
Joinpoint (connection point): The so-called connection point refers to the points that are intercepted. In spring, these points refer to methods because spring only supports connection points of method types.
Pointcut (pointcut): The so-called pointcut is the definition of which joinpoint we want to intercept.
Advice (Notification/enhancement): The so-called notification refers to the interception to Joinpoint after the thing to do is to inform. Notification is divided into pre-notification, post-notification, exception notification, final notification, surround notification (slice to complete the function)
Introduction (Introduction): Introduction is a special kind of notification without modifying the class code, Introduction can dynamically add methods or field to the class at run time.
Target object: The target object of the agent
Weaving (weaving): Refers to the process of applying the enhancement to the target object to create a new proxy object. Spring is woven with dynamic agents, while the ASPECTJ is woven into the stage with a compile-time weave and class mount.
Proxy: When a class is woven into an AOP, it produces a result proxy class aspect (tangent): a combination of pointcuts and notifications (referrals)

Two, the AOP in spring

Spring implements AOP primarily by the IOC container, which is responsible for generating and managing. There are two ways to create them:

    1. By default, the Java Dynamic agent is used to create an AOP proxy;
    2. When the class that needs the proxy is not the proxy interface, spring switches to using the Cglib proxy, or it can force the use of cglib. The higher version of spring automatically chooses whether to use the dynamic proxy or cglib to generate the proxy content, and of course we can force the use of the Cglib build agent, that is, there is a "Proxy-target-class" property, if this property value is set to True, Then the class-based proxy will work.
2.1 ASPECTJ supports 5 types of notification annotations:

[1] Before: Pre-notification, execution before method execution
[2] After: Post notification, executed after method execution
[3] Afterrunning: Returns a notification, executed after the method returns the result
[4] Afterthrowing: Exception notification, executed after the method throws an exception
[5] Around: Surround notification, around method execution
Among them, surround notification is the most common kind of notification annotations, especially in the use of the cache, for example: Spring-cache in the use of the service method to add a cache annotation, through AOP to intercept, if the cache already exists, then directly return the results, if not, Access to the service again.

2.2 Spring offers 4 ways to implement AOP:
    1. Classic Agent-based AOP
    2. @AspectJ annotation-driven facets
    3. Pure Pojo Facets
    4. Injection-type ASPECTJ facets
Iii. Overview of the Principles

Spring AOP Implementation principle is based on dynamic weaving dynamic agent technology, while ASPECTJ is static weaving, and dynamic agent technology is divided into Java JDK Dynamic agent and Cglib dynamic agent, the former is based on reflection technology implementation, the latter is based on the implementation of inheritance mechanism. Spring AOP also automates the timing of use when there are interfaces that automatically select the JDK Dynamic Agent technology, and if not, choose Cglib Technology, which is not as simple as the underlying implementation of spring AOP, and for easier generation of proxy objects, spring AOP Internal implementation of a focus on the generation of proxy objects of the factory class, so as to avoid a lot of manual coding, this is also very human, but the most important is the dynamic agent technology. In terms of performance, Spring AOP does not require special compiler assistance, but it does not perform better than aspectj static weaving.

See spring AOP for specific principles

Iv. Use of

Online to see others write a lot of examples of getting started, they are no longer elaborated, after all, their own food, the following is about the introduction of AOP information:
Why should we use AOP?
Implementation of AOP in spring
About AOP

The following is the use of their own in the personal site, is mainly used to count how much time the execution of a method consumes, the need to introduce Aopalliance.jar, Aspectj.weaver.jar and Spring-aspects.jar packages.

4.1 Opening AOP in spring MVC
    <!--自动扫描自定义切面-->    <aop:aspectj-autoproxy/>
4.2 Defining a slice
/** * 可以使用 @Order 注解指定切面的优先级, 值越小优先级越高 */@Order(2)@Aspect@Componentpublic class TimeInterceptor {}
4.3 Declaring a pointcut
    @Pointcut("execution(* com.myblog.service.impl.BlogServiceImpl.*(..))")    public void pointcut() {    }
4.4 Declaring a pre-pointcut
    @Before("pointcut()")    public void before(JoinPoint jp) {        logger.info(jp.getSignature().getName());        logger.info("----------前置通知----------");    }
4.5 Declaring a post-pointcut
    @After("pointcut()")    public void after(JoinPoint jp) {        logger.info("----------最终通知----------");    }
4.6 Surround Notification

Here, the special note is to throw the throwable exception, otherwise the method can not be processed when the error is not able to view

    @Around("execution(* (com.myblog.service.impl.*+&&!com.myblog.service.impl.AsyncServiceImpl).*(..))")    public Object timeAround(ProceedingJoinPoint joinPoint) throws Throwable {        Object obj = null;        Object[] args = joinPoint.getArgs();        long startTime = System.currentTimeMillis();        obj = joinPoint.proceed(args);        // 获取执行的方法名        long endTime = System.currentTimeMillis();        MethodSignature signature = (MethodSignature) joinPoint.getSignature();        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();        // 打印耗时的信息        this.printExecTime(methodName, startTime, endTime);        return obj;    }
4.7 Return result Notification
    @AfterReturning(pointcut = "execution(* com.myblog.service.impl.BlogServiceImpl.*(..))", returning = "result")    public void afterReturning(JoinPoint jp, Object result) {        logger.info(jp.getSignature().getName());        logger.info("结果是:" + result);        logger.info("----------返回结果----------");    }
4.8 Post-Exception notification
    @AfterThrowing(pointcut = "execution(* com.myblog.service.impl.BlogServiceImpl.*(..))", throwing = "exp")    public void afterThrowing(JoinPoint jp, Exception exp) {        logger.info(jp.getSignature().getName());        logger.info("异常消息:" + exp.getMessage());        logger.info("----------异常通知----------");    }
4.9 Results
2018-02-04 17:22:46.287 [http-nio-9090-exec-3] INFO com.myblog.aspect.timeinterceptor-getallblog2018-02-04  17:22:46.288 [http-nio-9090-exec-3] INFO com.myblog.aspect.timeinterceptor-----------Pre-notification----------2018-02-04 17:22:46.288 [http-nio-9090-exec-3] DEBUG Com.myblog.dao.blogmapper-cache hit Ratio [Com.myblog.dao.BlogMapper]: 0.62018-02-04 17:22:46.288 [http-nio-9090-exec-3] DEBUG Com.myblog.dao.blogmapper-cache hit Ratio [  Com.myblog.dao.BlogMapper]: 0.66666666666666662018-02-04 17:22:46.289 [http-nio-9090-exec-3] INFO Com.myblog.cache.EhRedisCache-===========================cache L1 (ehcache) 2018-02-04 17:22:46.292 [ Http-nio-9090-exec-3] INFO Com.myblog.aspect.timeinterceptor-com.myblog.service.iblogservice.getallblog method Take time: **5 ms**2018-02-04 17:22:46.292 [http-nio-9090-exec-3] INFO com.myblog.aspect.timeinterceptor-----------Final Notice----------2018-02-04 17:22:46.292 [http-nio-9090-exec-3] INFO com.myblog.aspect.timeinterceptor-getallblog2018-02-04 17:22:46.292 [http-nio-9090-exec-3] INFO Com.myblog.aspect.TimeInterceptor-the result is: Page{count=true, Pagenum=1, Pagesize=15, Startrow=0, endrow=15, total=462, pages=31, countsignal=false, orderby= ' null ', Orderbyonly=false,  Reasonable=true, pagesizezero=true}2018-02-04 17:22:46.292 [http-nio-9090-exec-3] INFO  com.myblog.aspect.timeinterceptor-----------return results----------2018-02-04 17:22:46.292 [http-nio-9090-exec-3] INFO Com.myblog.cache.EhRedisCache-===========================cache L1 (Ehcache): {mycache}{ com.myblog.service.impl.blogserviceimpl.getbanner}={[key = Com.myblog.service.impl.BlogServiceImpl.getBanner, Value=[[email protected], [email protected], [email protected], [email protected], [email  protected]], version=1, hitcount=2, creationtime = 1517736161430, LastAccessTime = 1517736166292]}

From the results can be seen, the entire method of execution time is 5ms, it is objective, if too large to optimize it.

The main source code in this:

Timeinterceptor

can also download my blog source Reference reference:
Newblog

Reference
    1. Spring Learning summarizes the many ways--spring implements AOP
    2. Spring AOP Basics Introductory Summary One
    3. Spring AOP Official

Spring AOP Small Note

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.