使用注解时未调用@Aspect

问题描述

我创建了一个注释,以使某些操作如下:

teams/league/3

和一个方面:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Verify {
}

和配置:

@Aspect
@Component
public class VerifyAspect {
    @Before("execution(public * *(..,@Verify (*),..))")
    public void actionBefore(JoinPoint joinPoint) {
       System.out.println(joinPoint); // <<-------------- can't see this message
    }
}

但是当我打电话时:

@Configuration
@EnableAspectJAutoProxy
public class VerifyConfig {
}

根本没有调用方面。我在创作中会犯任何错误吗?

解决方法

spring docs开始:Spring AOP当前仅支持方法执行连接点(建议在Spring bean上执行方法)-因此,请确保您正在调用的方法

public void method(@Verify MyObject obj){
   // do something
}

在其中一个Spring Bean中声明。

根据您共享的代码,我创建了一个简单的演示:

还请确保Aspectjweaver.jar位于您的依赖项中

pom.xml

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>

主要应用

@SpringBootApplication
public class AspecjStyleAopApplication {

    public static void main(String[] args) {
        SpringApplication.run(AspecjStyleAopApplication.class,args);
    }

}

配置

在这里,请确保为Spring提供正确的basePackages以扫描您的组件

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.example")
public class AspectJConfig {
}

注释

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Verify {
}

尊重

@Aspect
@Component
public class VerifyAspect {

    @Before("execution(public * *(..,@Verify (*),..))")
    public void actionBefore(JoinPoint joinPoint) {
        System.out.println("THIS SHOULD BE DISPLAYED");
        System.out.println(joinPoint); // <<-------------- can't see this message
    }
}

服务

@Service
public class SampleService {

    public void method(@Verify Object obj){
        System.out.println("Passed object: " + obj);
    }
}

RestController

@RestController
public class SampleRestController {

    private final SampleService sampleService;

    public SampleRestController(SampleService sampleService) {
        this.sampleService = sampleService;
    }

    @GetMapping("/sample")
    public String sampleRestMethod() {
        sampleService.method(5);
        return "It works";
    }
}

当我调用http://localhost:8080/sample端点时,来自控制台的输出:

THIS SHOULD BE DISPLAYED
execution(void com.example.aspecjstyleaop.SampleService.method(Object))
Passed object: 5

第二行是您要打印的内容。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...