Parsing Spring Day (aspect-oriented AOP)

Aspect-Oriented: AOP

Basis without source code modification on the method of enhanced. AOP is the underlying principle of agent technology (the first: the jdk dynamic proxy (programming must have interfaces) second:.. Cglib agent technology (subclass generate class) if there are programs written excuse, the spring frame It will automatically use jdk dynamic proxy technology enhancements).

JoinPoint (connection point) are those so-called point of attachment points being intercepted. In the spring, these points refers to a method, because only the spring supporting method junction type

Pointcut (entry point) - the so-called entry points means we have to intercept the definition of what Joinpoint

Advice (notification / enhanced) - the so-called notification means after intercepting Joinpoint have to do is to be divided into pre-notification notification notification, rear, throws advice, final notice, around advice (section functions to be performed).

Target (target audience) - Agents of the target object

Weaving (weaving) - refers to the enhancements to the target object to create a new proxy object process

The Proxy (agent) - a class after being woven reinforcing AOP, to produce a result proxy class

Aspect (section) - is a combination of entry points and notification, and later to write their own configuration

 Create a common project to introduce Maven coordinates

 1 <dependencies>
 2     <dependency>
 3         <groupId>org.springframework</groupId>
 4         <artifactId>spring-context</artifactId>
 5         <version>5.0.2.RELEASE</version>
 6     </dependency>
 7     <dependency>
 8         <groupId>commons-logging</groupId>
 9         <artifactId>commons-logging</artifactId>
10         <version>1.2</version>
11     </dependency>
12     <dependency>
13         <groupId>log4j</groupId>
14         <artifactId>log4j</artifactId>
15         <version>1.2.12</version>
16     </dependency>
17     <dependency>
18         <groupId>org.springframework</groupId>
19         <artifactId>spring-test</artifactId>
20         <version>5.0.2.RELEASE</version>
21     </dependency>
22     <dependency>
23         <groupId>junit</groupId>
24         <artifactId>junit</artifactId>
25         <version>4.12</version>
26     </dependency>
27   
28         <!-- AOP联盟 -->
29         <dependency>
30             <groupId>aopalliance</groupId>
31             <artifactId>aopalliance</artifactId>
32             <version>1.0</version>
33         </dependency>
34         <!-- Spring Aspects -->
35         <dependency>
36             <groupId>org.springframework</groupId>
37             <artifactId>spring-aspects</artifactId>
38             <version>5.0.2.RELEASE</version>
39         </dependency>
40         <!-- aspectj -->
41         <dependency>
42             <groupId>org.aspectj</groupId>
43             <artifactId>aspectjweaver</artifactId>
44             <version>1.8.3</version>
45         </dependency>
46   </dependencies>
  • Create a Spring configuration file, the introduction of schema constraints specific to AOP

     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:context="http://www.springframework.org/schema/context"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        xsi:schemaLocation="
     7                 http://www.springframework.org/schema/beans
     8                 http://www.springframework.org/schema/beans/spring-beans.xsd
     9                 http://www.springframework.org/schema/context
    10                 http://www.springframework.org/schema/context/spring-context.xsd
    11                 http://www.springframework.org/schema/aop
    12                 http://www.springframework.org/schema/aop/spring-aop.xsd">
    13     
    14 </beans>
  • Create a package structure to prepare specific interface and implementation class
    . 1  Package cn.tx.demo2;
     2  public  class UserServiceImpl the implements UserService {
     . 3  . 4     @Override
     . 5 public void Save () {
     . 6          System.out.println ( "business layer: Save User ..." );
     7     }
     8 9 }         
  • The target class configuration with Spring
    <bean id="userService" class="cn.tx.demo2.UserServiceImpl"/>
  • Custom cut class
    . 1  Package cn.tx.demo2;
     2  . 3 / ** . 4 * custom aspects pointcut class = (expression) + notification (enhanced code)
     . 5 * / . 6 public class MyXmlAspect {
     . 7 . 8 / ** . 9      * notification
     10 * / 11 public void log () {
     12 // send SMS
     13 // send messages / logs / transaction management 14 15          System.out.println ( "enhanced implementation of the method ..." );
     16     }
     . 17 18 is } 
       
            
           
                            
       
  • Class is defined in the profile section

    1 <bean id="myXmlAspect" class="cn.tx.demo2.MyXmlAspect"/>
  • Aop complete configuration in the configuration file

    1    <! - Enhanced configuration of AOP ->
     2      <AOP: config>
     . 3          <! - pointcut + = notification section configured Composition ->
     . 4          <AOP: Aspect REF = "myXmlAspect">
     . 5              <-! pre-notification: UserServiceImpl before performing the save method, enhances ->
     . 6              <AOP: before method = "log" = the pointcut "execution (public void cn.tx.demo2.UserServiceImpl.save ())" />
     . 7          < / AOP: Aspect>
     . 8      </ AOP: config>
  • To enhance test
    package cn.tx.test;
    import cn.tx.demo2.UserService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext_demo2.xml")
    public class Demo2 {
        @Autowired
        private UserService userService;
        /**
         * Test
         */
        @Test
        public void run1(){
            userService.save();
        }
    }
  • Expression format entry points:
    • Execution ([Modifier] return type package name. class name. Method name (parameter))

    • Modifiers can be omitted, is not required to appear.

    • The return value type can not be omitted to write, to write the return value according to your approach. You can use * instead.

    • For example the package name: com.tx.demo3.BookDaoImpl

      • First com can not be omitted to write, but you can use instead of *
      • Intermediate may be used instead of the package name * Number
      • If you want to omit the intermediate package names may be used ..
    • Class name can be used instead of the asterisk, it had a similar wording: * DaoImpl

    • The method may be used instead of an asterisk

    • If the parameter is a parameter can be used instead of an asterisk, if you want to represent any parameter ..

  • AOP way of notification
     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:context="http://www.springframework.org/schema/context"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        xsi:schemaLocation="
     7                 http://www.springframework.org/schema/beans
     8                 http://www.springframework.org/schema/beans/spring-beans.xsd
     9                 http://www.springframework.org/schema/context 
    10                  HTTP: // www.springframework.org/schema/context/spring-context.xsd 
    11                  HTTP: // www.springframework.org/schema/aop 
    12                  HTTP: // the WWW. springframework.org/schema/aop/spring-aop.xsd "> 
    13 is  
    14      <-! the bean management ->
     15      <the bean ID =" that userService " class =" cn.tx.demo1.UserServiceImpl "/>
     16  
    . 17      < ! - ================= write AOP configuration file ==================== ->
     18      <! - configure aspect class ->
     . 19      <the bean ID = "myXmlAspect" class= "cn.tx.demo1.MyXmlAspect" />
     20 is  
    21 is      ! <- AOP enhanced configuration ->
     22 is      <AOP: config>
     23 is          ! <- section is arranged, the introduction of the real cut the object ->
     24          <AOP : Aspect ref = "myXmlAspect">
     25              <- is pre-configured notifications:! target object before execution method, first enhancement. method = "notification method aspect class" pointcut = "pointcut expression" ->
     26              <!
                                                 Class name * * recommended wording the ServiceImpl example: UserServiceImpl DeptServiceImpl
     33 is                      a method of writing Recommended Name *: * Save
     34 is                      a method == parameter list .. Object obj Object ... type of variable parameters
     35                      <AOP: before Method = "log" = the pointcut "execution (.. * cn.tx ServiceImpl.save * * * (..))" />
     36              ->
     37 [  
    38 is              <-!
     39                  notification type
     40                      before advice: before performing the target object method, first enhancement.
    41 is                      <AOP: before Method = "log" = the pointcut "Execution (cn.tx * * * * ServiceImpl.save (..)..)" />
     
    the finally 
    44 is                      <AOP: After Method = "log" = the pointcut "Execution (.. * cn.tx ServiceImpl.save * * * (..))" />
     45  
    46 is                      after advice: audiences method succeeded, will enhancement.
    47                      <AOP: After returning-Method = "log" = the pointcut "Execution (cn.tx * * * * ServiceImpl.save (..)..)" />
     48  
    49                      abnormality notification: audiences method fails, only enhancement.
    50                      <AOP: After the throwing-Method = "log" = the pointcut "Execution (cn.tx * * * * ServiceImpl.save (..)..)" />
     51 is  
    52 is                      <AOP: Method = before "the begin" the pointcut = "Execution (cn.tx *. *. * * ServiceImpl.save (..))" />
     53 is                     <AOP: After returning-Method = "the commit" the pointcut = "Execution (cn.tx * * * * ServiceImpl.save (..)..)" />
     54 is                      <AOP: After the throwing-Method = "ROLLBACK" the pointcut = "Execution (.. * cn.tx ServiceImpl.save * * * (..))" />
     55                      <AOP: After Method = "Close" the pointcut = "Execution (cn.tx * * * * ServiceImpl.save.. (..)) "/>
     56 is  
    57 is                      around advice: decide enhanced position. Use the around advice, the target object's default method, there is no need to manually perform the execution of the target object method.
    58              ->
     59  
    60              <AOP: around Method = "logAroud" = the pointcut "Execution (cn.tx * * * * ServiceImpl.save (..)..)" />
     61 is  
    62 is          </ AOP:
     
     </beans>

    Spring's AOP technology - annotate way

  • Also create a common Maven project, import coordinate, write an interface, ibid.
  • Write an aspect class, to cut class to add annotations @Aspect, prepared by the method of strengthening, using the notification type annotation statement
    . 1  Package cn.tx.demo3;
     2  . 3 Import org.aspectj.lang.annotation.Aspect;
     . 4 Import org.aspectj.lang.annotation.Before;
     . 5 Import org.springframework.stereotype.Component;
     . 6 12 is @Component   / / the IOC to manage class to 13 is @Aspect      // declaration is cut class == <AOP: Aspect REF = "myXmlAspect"> 14 public class MyAnnoAspect {
     15 16 / ** . 17      * notification method
     18 * / 19 // @Before (value = "entry point expression")    
    
    
            
           
         
    20     @Before(value = "execution(public * cn.tx.demo3.OrderServiceImpl.save(..))")
    21     public void log(){
    22         System.out.println("增强了...");
    23     }
    24 25 }
    26

     

  • Opened automatic proxy configuration file

     

    <aop:aspectj-autoproxy/>

     

  • testing method

     1  
     2 package cn.tx.test;
     3  4 import cn.tx.demo2.UserService;
     5 import cn.tx.demo3.OrderService;
     6 import org.junit.Test;
     7 import org.junit.runner.RunWith;
     8 import org.springframework.beans.factory.annotation.Autowired;
     9 import org.springframework.test.context.ContextConfiguration;
    10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    11 
    12 
    13 @RunWith(SpringJUnit4ClassRunner.class)
    14 @ContextConfiguration("classpath:applicationContext_demo3.xml")
    15 public class Demo3 {
    16 17     @Autowired
    18     private OrderService orderService;
    19 20     /**
    21      * 测试
    22      */
    23     @Test
    24     public void run1(){
    25         orderService.save();
    26     }
    27 28 }

     

  • Notification type annotations

    . 1 @Before - Pre-notification
     2  
    . 3 @AfterReturing - after advice
     . 4  
    . 5 @Around - around the notification (the target object does not perform the default method, performed manually)
     . 6  
    . 7 @After - Final Notice
     8  
    9 @AfterThrowing - an exception is thrown notice

     

  • Pure annotation style

    package cn.tx.demo3;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    
    @Configuration       // configuration class 
    @ComponentScan (value = "cn.tx.demo3")    // scan package 
    @EnableAspectJAutoProxy      // turn on the automatic proxy == <AOP: AspectJ-the autoproxy /> 
    public  class SpringConfig {
        
    }

     

     

Guess you like

Origin www.cnblogs.com/LBJLAKERS/p/11750094.html