(5) AOP section to learn programming --Spring Review

Author: Chen Buyi
www.cnblogs.com/chenbenbuyi

Spring series of articles
(1) a thorough understanding of the Spring container and application contexts --Spring review learning
(2) DI / IOC and AOP principle acquaintance --Spring review learning
(3) automated assembly bean - Spring retrospective study
(4) through Java annotations and XML configuration assembly bean - Spring retrospective study
(5) AOP programming --Spring review section to learn learning --Spring review

A basic understanding

  AOP, Aspect Oriented Programming, as one of Spring's core idea, there are too many tutorials ah, ah explain the degree of your mother, but bloggers still have to follow their own ideas and understanding come to elaborate. The reason is simple, after all, is someone else's ideas of others, their understanding is their own, especially when the words, to explain the code after it again, it seems that the level of understanding becomes different.

  Bloggers do not explain the conceptualization AOP, here simply to say why you want to use under the idea of ​​such a program and related AOP technology. Actually very simple, is to decouple between business modules, with particular emphasis on high cohesion, low coupling in the modern software design, our business requires modular, each functional module is only concerned with their own logic implementation, rather than the main concern business logic unrelated features. However, in object-oriented system design, the system essential functions such as logging, transactions are scattered throughout the primary application of highly coupled logic code, which makes the main service redundant code becomes quite difficult to reuse . In the aspect-oriented programming ideas, we will consider those repetitive application of the code spread in many pulled out of the package to be modular functional class, the main business logic to make a more focused, simple, and secondly modular logs, transaction also facilitates reuse and portability, this is the decoupling idea. However, decoupling does not mean broken coupling, pulled out of function and ultimately to somehow "also" (qie) back, otherwise the application will not function improved. Here, "also" (qie) back AOP technology is technology, and this idea is decoupled programming AOP programming ideas. In ecology of Java, provide technical AOP framework, there are many, it is the main use of Spring AOP and Spring "drawing" and included into the AOP AspectJ's own ecosystem.

Two core concepts

  For ease of understanding elaborated, bloggers first few nagging. The basic set forth above, we know that, AOP to do things is actually very simple, object-oriented programming is to get in, pulled out of the module code (permissions, logging, transaction) also (qie) back, but it certainly can not be the object thinking miscellaneous code combinations, but should be more clever some of the best can unknowingly in the course of execution of the original business code also (qie) back - the process that is to be performed in the main business logic in before dynamically add (permissions, logging, transaction) Code pulled doing those things. How can you do it? By proxy ah, the pro! Think about it, we use a proxy for a target object not just to the target object logic execution time by doing something extra point in the proxy object in it? Thus, although the original target object and does not add any extra functionality, by some secret agents of Sao operation, presented to the caller as if the target object has the proxy those extra features like object. So you have a good understanding of how to use Spring's AOP in a dynamic proxy. Well, after some nagging, related terms we will look at the AOP will be much better understood -

1, crosscutting concerns

  As described above, we have logs, transactions, permissions and other high repeatability of the code was spread in various parts of the application's functionality called crosscutting concerns.

2, the connection point (Join Point)

  The proxy target object during the execution of business logic, can be cut into a dynamic proxy object node agent of some timing functions, such as methods before and after the execution, exception, successfully returns and so on. Of course, this is only for the Spring it, because based on dynamic proxy AOP Spring, only supports method-level cut, in fact, AOP framework of AspectJ, JBoss, etc., and also provides more fine-grained field constructors such as a connection point support.

3, notice (Advice)

  As described above, what is the proxy object in the target object to the timing of the additional function code, so a lot of tutorial information on enhanced call. Please note that the blogger's description of the notification mentioned what opportunity, it is well understood, the proxy object you add additional features to give the target audience, in which he will have a clear opportunity to increase it, so we cut the notice in accordance with the function timing divided into the following five types:

  • Pre-notification (Before): notification code to be executed before the proxy object is called the target method;
  • After returning advice (After): an enforcement notice after the code is executed to complete the proxy object target method, regardless of whether the method successfully executed (which is equivalent to the meaning of the exception caught in the finally block will always be executed, so that if bloggers will be named to better understand the ultimate notice some);
  • Abnormality notification (After-throwing): code execution notice is thrown proxy object target method;
  • A return notification (After-returning): code execution notice is successfully performed proxy object target method;
  • Surround notification (Around): the target method is wrapped in the proxy object, corresponding to all of the above combined notification types.

4, tangent point (Pointcut)

  The target method is performed during the proxy object to execute a real notification code or a plurality of connection points, which will be matched by a pointcut expression language.

5, section (Aspect)

  Binding notification and tangent point, a complete section includes three basic elements of the target object proxy object notify: when (before, after, abnormal, surround, returns, etc.), where (cut point), do (notification cut function).

6, weaving (Weaving)

  The process is applied to the cut surface and creates proxy objects proxy object. Section will be woven into the proxy object performing the method specified in the connection point (contact point). In fact, the proxy object life cycle, there are multiple occasions (compiler, class load, run) can be woven into it Spring, the proxy object is created in the proxy object runtime, woven into the logic section .

Note: The above description is based on Spring AOP method level to elaborate

Three basic code sample

  He said so much, or the code is the most simple and direct. Ready to work:

  ① test dependent packages and their version (Note: Many tutorials are referred to the need aopalliance package, but bloggers testing process and the necessity of this package there is no confirmation)

aspectjweaver-1.9.2.jar
commons-logging-1.2.jar
spring-aop-4.3.18.RELEASE.jar
spring-beans-4.3.18.RELEASE.jar
spring-context-4.3.18.RELEASE.jar
spring-core-4.3.18.RELEASE.jar
spring-expression-4.3.18.RELEASE.jar
spring-test-4.3.18.RELEASE.jar

  ② define two base model class (below), business is: to only add a camera phone to call dynamic function, play games such non-primary business functions.

//主业务功能
public class HuaWeiPhone  {
    public void ring() {
        System.out.println("华为手机,产销第一");
    }
}

//额外添加的功能
public class Photograph {

    public void  takePictures(){
        System.out.println("华为手机,拍照牛批");
    }

    public void  playGames(){
        System.out.println("华为手机,游戏玩得也这么畅快");
    }
}

1, XML configuration way

  According to the above Java code, a very simple configuration, you can see the dynamic for mobile phones increases the effect of the camera

<bean  class="main.java.model.HuaWeiPhone"/>
    <bean id="photograph" class="main.model.Photograph"/>
    <aop:config>
        <aop:pointcut id="ring" expression="execution(* main.model.HuaWeiPhone.ring(..))"/>
        <aop:aspect  ref="photograph">
            <aop:before method="takePictures" pointcut-ref="ring"/>
            <aop:after method="playGames" pointcut-ref="ring"/>
        </aop:aspect>
    </aop:config>

  In Spring environmental testing class XML configuration -

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:main/resource/applicationContext.xml")
public class SpringTest {

    @Autowired
    HuaWeiPhone huaWeiPhone;

    @Test
    public void testXml(){
        huaWeiPhone.ring();
    }
}

Output
Here Insert Picture Description

2, Java annotations way

  We need to explain that, Spring annotation-based AOP actually learn from and absorb the AspectJ features, so you will see a lot of similar AspectJ annotation framework. On the previous model class transformed into a section by adding the appropriate annotations -

@Aspect  //将该类标注为一个AOP切面
@Component
public class Photograph {

    @Pointcut("execution(* main.model.HuaWeiPhone.ring(..))")
    public void chenbenbuyi (){}


    @Before("chenbenbuyi()")
    public void  takePictures(){
        System.out.println("华为手机,拍照牛批");
    }

    @After("chenbenbuyi()")
    public void  playGames(){
        System.out.println("华为手机,游戏玩得也这么畅快");
    }
}

  Likewise, we must also add the target class (HuaWeiPhone) @Componet notes be handed over to the Spring container management. Then, if it is pure annotation, then, but also a configuration class -

//配置注解扫描
@ComponentScan(basePackages = "main")
//启用AspectJ的自动代理功能
@EnableAspectJAutoProxy
public class JavaConfig {
}

  Finally, in the Spring of environmental tests -

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = "classpath:main/resource/applicationContext.xml")
@ContextConfiguration(classes = JavaConfig.class)
public class SpringTest {

    @Autowired
    HuaWeiPhone huaWeiPhone;

    @Test
    public void testAnno(){
        huaWeiPhone.ring();
    }
}

  The results above, there is not demonstrated. But note that, no matter what the configuration, the premise of Spring AOP programming is based on the object you want to inform and be informed method to Spring IOC container management, which is to be declared as the Spring container Bean.

Four needs upgrade

  In the third part, bloggers just shows the most simple realization of AOP functionality, there are slightly more complicated skill points is not listed. For example, five advice kinds of surround notice it? Another example, my section of code if you want to pass parameters how to do it? Next bloggers turn to explain.

  ① use around advice on
  the basis set forth in two, five advice kinds in around advice is the most powerful, in fact, we can customize the front in around advice in personalized post, notify and return to the type of exception , and if the individual uses front, rear and other types of notifications, if the business involves changes to the multi-threaded member variables, concurrency issues that may arise, it is surrounded by other than individual use several types of notifications more secure. We make changes based around advice of the above section, to include all types of notification feature

@Aspect
@Component
public class Photograph {

    @Pointcut("execution(* main.model.HuaWeiPhone.ring(..))")
    public void chenbenbuyi (){}

    @Around("chenbenbuyi()")
    public void  surround(ProceedingJoinPoint joinPoint){
        try {
            System.out.println("目标方法执行前执行,我就是前置通知"); 
            joinPoint.proceed();// ①
//            int i =1/0;       // ②  制造异常
            System.out.println("正常返回,我就是返回通知");
        } catch (Throwable e) {
            System.out.println("出异常了,我就是异常通知");
        }finally {
            System.out.println("后置通知,我就是最终要执行的通知");
        }
    }
}

  Like other XML-based configuration and type of the above notice, but the element tags for <aop: around /> only. The upper position corresponding to the print statement on the timing logic section performs several other types of notification. Note here that the notification method body around the target requires an interface method ProceedingJoinPoint as parameters in the surround notification, proceed by performing the parameter () method calls the notification of cut required. If the call does not perform at ①, it is in fact the notification method will be blocked off, so you will see clearly to perform the test method to be notified, but not the actual execution. The parameter object can also get method signature, proxy object, the target object and other information, you can test yourself with the play.

  ② on parameter passing problem notification
  section, although general logic, but the actual cut in the different target, it may still want to notify method (such as different parameters), depending on the method of notification to perform different logic, which requires our advice can be passed to obtain notification method parameters. By cutting point expression, it is also very easy to do. First, we modify the method to be notified can pass parameters:

 public void ring(String str) {
        System.out.println("华为手机,产销第一");
        int i =1/0;
 }

Then cut cut cut point expressions and methods to make the corresponding changes -

@Aspect
@Component
public class Photograph {
    /**
     * Spring 借助于 AspectJ的切点表达式语言中的arg()表达式执行参数的传递工作
     */
    @Pointcut("execution(* main.model.HuaWeiPhone.ring(String))&&args(name)")
    public void chenbenbuyi (String name){}

    /**
     *  ① 在引用空标方法的切点表达式时同时也就要传入相应的参数
     *  ② 传入的参数形参名字必须和切点表达式中的相同
     */
    @Before("chenbenbuyi(name)")
    public void  takePictures(String name){
        System.out.println("喂喂,你好我是 "+ name);
    }

    /**
     *  对于异常通知,有专门的异常参数可以直接获取到被通知方法出现异常后信息的
     */
    @AfterThrowing(pointcut = "chenbenbuyi(name)",throwing = "e")
    public void  excep(String name,Throwable e){
        System.out.println("出异常了,异常信息是:"+e.getMessage());
    }
}

  XML configuration parameters passed

    <bean  class="main.java.model.HuaWeiPhone"/>
    <bean id="photograph" class="main.java.model.Photograph"/>
    <aop:config>
        <aop:pointcut id="ring" expression="execution(* main.java.model.HuaWeiPhone.ring(..)) and args(name)"/>
        <aop:aspect  ref="photograph">
            <aop:before method="takePictures" pointcut-ref="ring" arg-names="name" />
            <aop:after-throwing method="excep"  throwing="e" arg-names="name,e" pointcut-ref="ring"/>
        </aop:aspect>
    </aop:config>

  Test code

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = "classpath:main/resource/applicationContext.xml")
@ContextConfiguration(classes = JavaConfig.class)
public class SpringTest {

    @Autowired
    HuaWeiPhone huaWeiPhone;

    @Test
    public void testAnno(){
        huaWeiPhone.ring("博客园 陈本布衣");
    }
}

  The final results of the test execution
Here Insert Picture Description
  Precautions:

  • ① XML configuration since the & symbol has a special meaning, so when the tangent point connection parameter name expression no longer be used in the annotation &&, but should be used in place of and, if there is the same or (||) not (! ) operation, and are not used or replaced.
  • ② annotations and XML configuration parameter cut-off point expression to describe the type of local bloggers adopt a different approach, because ... it means any type, you can not specify.

Five cut-point expressions are used to illustrate

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_40914991/article/details/91402587