Spring- use annotations to achieve AOP (IX)

Notes achieve AOP code flow becomes extremely simple, but we need to understand is what the principle is.

Add a few notes in our custom AOP implementation can be achieved in

important point:

Write comments section -> Aspect

The starting point can be written directly on the enhancement plus the corresponding notes on it.

Adding annotations profile automatic agent identification code .----> [<aop: aspectj-autoproxy />]

 

Audience unchanged userService and userServiceImpl

Package org.west.anno; 

        Import org.aspectj.lang.annotation.After;
         Import org.aspectj.lang.annotation.Aspect;
         Import org.aspectj.lang.annotation.Before; 

// section annotation 
@Aspect
 public  class Anno {
     //    entry points can be written directly enhance the above 
    @Before ( "Execution (org.west.service.UserServiceImpl *. * (..))" )
     public  void the before () { 
        System.out.println ( "---- -> before the method is performed " ); 

    } 


    @After ( ." execution (org.west.service.UserServiceImpl * * (..)) " )
     public  void After () {
        (System.out.println "after ------> method performs" ); 
    } 

}

Note notes before and after the package to guide right, yes Aspectj package.

Spring's core configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean对象-->
    <bean id="userService" class="org.west.service.UserServiceImpl"/>
<! - annotation achieve AOP class -> 
    <bean the above mentioned id = "Anno"class = "org.west.anno.Anno" /> 
! <- automatic agent identification annotation -> 
     <AOP: AspectJ-the autoproxy /> 

    
</ Beans>

Test categories:

public class TestDemo {
    @Test
    public void test() {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");

        UserService userService = (UserService) context.getBean("userService");

        userService.add();

    }

AOP Summary:

  • Nature is dynamic proxy

  • Required to a packet, to be woven into the package aop: aspectjweaver

  • Be careful not to miss the cut;

  • Three ways to achieve the AOP

    • Use SpringAPI to achieve AOP

    • Use custom classes to implement AOP

    • Use annotations to achieve AOP

 

Guess you like

Origin www.cnblogs.com/xiaoqiqistudy/p/11305378.html