sun*_*leo 1 java spring annotations spring-boot
我有 myannotation,每当我的方法(有 myannotation)被执行时,就应该调用 AOP,但它在我的 Spring Boot 控制器中不起作用。但是它适用于具有其他注释的方法。请帮助我了解会发生什么。
更新:我的注释
@Retention(RUNTIME)
@Target({ METHOD, CONSTRUCTOR })
public @interface MyAnnotation {
}
@Aspect
@Component
public class AnnotationAspect {
private static final String POINTCUT_METHOD1 = "@annotation(com.somepackage.MyAnnotation)";
@Around(POINTCUT_METHOD1)
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
try {
System.out.println("Beforeee " + joinPoint);
joinPoint.proceed();
} finally {
System.out.println("Afterrr " + joinPoint);
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
场景一:(工作中)
@Controller
@RequestMapping("user")
public class ArticleController {
@GetMapping("article/{id}")
@MyAnnotation // here it is
public ResponseEntity<String> getArticleById(@PathVariable("id") Integer id)
{
return new ResponseEntity<String>(dummyMethod(), HttpStatus.OK);
}
public String dummyMethod() {
System.out.println("Dummy method with MyAnnotation");
return "HelloWorld!";
}
}
Run Code Online (Sandbox Code Playgroud)
日志:(工作中)
Beforeee execution(ResponseEntity com.mypackage.getArticleById(Integer))
Dummy method with MyAnnotation
Afterrr execution(ResponseEntity com.mypackage.getArticleById(Integer))
Run Code Online (Sandbox Code Playgroud)
场景2:(不工作)
@Controller
@RequestMapping("user")
public class ArticleController {
@GetMapping("article/{id}")
public ResponseEntity<String> getArticleById(@PathVariable("id") Integer id)
{
return new ResponseEntity<String>(dummyMethod(), HttpStatus.OK);
}
@MyAnnotation //here it is
public String dummyMethod() {
System.out.println("Dummy method with MyAnnotation");
return "HelloWorld!";
}
}
Run Code Online (Sandbox Code Playgroud)
日志:(不工作)
Dummy method with MyAnnotation
Run Code Online (Sandbox Code Playgroud)
场景 3:(不工作)
@Service
public class ArticleService {
@MyAnnotation //here it is
public String dummyMethod() {
System.out.println("Dummy method with MyAnnotation");
return "HelloWorld!";
}
}
Run Code Online (Sandbox Code Playgroud)
它可能不起作用,因为您从同一个类调用 dummyMethod() 。尝试将 dummyMethod() 移至另一个服务类。原因是同一类内的调用不会通过 Spring 代理。对 getArticleById() 的调用是代理的,将由 AOP 处理,但 dummyMethod() 也可能是私有方法。
| 归档时间: |
|
| 查看次数: |
3716 次 |
| 最近记录: |