AOP中获取自定义注解的参数值

目录

1、利用注解实现AOP的基本流程

  1.1、创建一个注解,用来注解切点(pointcut)

  1.2、创建一个service,使用上面定义的注解来指定切点

  1.3、创建Aspect,增加业务逻辑

  1.4、创建Spring配置类

  1.5、测试

2、获取自定义注解的参数  

Spring中,可以通过自定义注解的方式来实现AOP,比如下面简单的示例:

1.1、创建一个注解,用来注解切点(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、创建一个service,使用上面定义的注解来指定切点

  这里为了节约篇幅,就不创建service接口,再创建serviceImpl来实现接口了,直接写在service中:

package cn.ganlixin.service;

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

@Service
public class DemoService {

    @DemoAnnotation  // 使用自定义的注解,声明该方法为切点方法
    public void demo() {
        System.out.println("this is DemoService.demo()");
    }
}

  

1.3、创建Aspect,增加业务逻辑

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、创建Spring配置类

  主要做的是:指定包扫描路径

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、测试

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();
    }
}

  输出:

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

  

猜你喜欢

转载自www.cnblogs.com/-beyond/p/11387487.html
今日推荐