如何解决使用注解时未调用@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
第二行是您要打印的内容。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。