AOP acquired parameter values for custom annotations

table of Contents

1, the use of annotations to achieve the basic process of AOP

  1.1, create a note for comment tangent point (pointcut)

  1.2, create a service, as defined above using annotations to specify the cut point

  1.3, create Aspect, increase business logic

  1.4, create a Spring configuration class

  1.5 Test

2, get custom parameter annotations  

 

Spring, AOP may be achieved by way of custom annotations, such as the following simple example:

 

1.1, create a note for comment tangent point (pointcut)

package cn.ganlixin.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DemoAnnotation {
    //注意这里没有定义属性
}

  

1.2, create a service, as defined above using annotations to specify the cut point

  Here in order to save space, do not create service interfaces, and then create serviceImpl to implement the interface, and write directly in the service:

cn.ganlixin.service Package; 

Import cn.ganlixin.annotation.DemoAnnotation; 
Import org.springframework.stereotype.Service; 

@Service 
public class the DemoService { 

    @DemoAnnotation // use custom annotations, the method is declared as the cutoff point method 
    public void Demo () { 
        System.out.println ( "IS DemoService.demo the this ()"); 
    } 
}

  

1.3, create Aspect, increase business logic

package cn.ganlixin.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class DemoAspect {

    @Before("@annotation(cn.ganlixin.annotation.DemoAnnotation)")
    public void demoBefore() {
        System.out.println("this is before output message");
    }
}

  

1.4, create a Spring configuration class

  Mainly it does is: Specifies the package scan path

package cn.ganlixin;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("cn.ganlixin")
@EnableAspectJAutoProxy
public class AppConfig {
    
}

  

1.5 Test

package cn.ganlixin;

import cn.ganlixin.service.DemoService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppTest {

    @Test
    public void testAOP1() {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        DemoService demoService = context.getBean(DemoService.class);
        demoService.demo();
    }
}

  Output:

this is before output message
this is DemoService.demo()

  

 

Guess you like

Origin www.cnblogs.com/-beyond/p/11387487.html