我有扩展具有 @Annotation1 注释的 BaseService 类的服务类。在 @Annotation1 中还有另一个注释 - @Annotation2。
我希望能够创建方面方法,该方法在使用 @Annotation2 注释的类中的所有方法之前运行,因此在扩展 BaseService 类的任何服务中。
@Annotation1
abstract class BaseService {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Annotation2
public @interface Annotation1 {
}
@Target(value = {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Annotation2 {
}
public class TestService extends BaseService {
private void testMethod(){
// does some service task
}
}
@Aspect
public class TestAspect {
@Before("@within(com.example.Annotation2) ||" +
" within(@(@com.example.Annotation2 *)*)" +
" @annotation(com.example.Annotation2)")
public void aspectMethod(JoinPoint joinPoint) {
// should run before testMethod
}
}
方面方法aspectMethod()应该在TestService中的testMethod()之前运行 但没有。
最佳答案
根据my other answer我本来期望这样的方面能够发挥作用:
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class TestAspect {
@Before(
"execution(* *(..)) && (" +
"within(@de.scrum_master.app.Annotation2 *) || " +
"within(@(@de.scrum_master.app.Annotation2 *) *) || " +
"within(@(@(@de.scrum_master.app.Annotation2 *) *) *)" +
")"
)
public void myAdvice1(JoinPoint joinPoint) {
System.out.println(joinPoint);
}
}
不幸的是它没有,这似乎是 AspectJ 的限制。我创建了Bugzilla ticket #549437为此,您可能想要关注。
解决方法:直接注释 TestService
。
关于java - 用于具有位于另一个注释内的注释的类中的方法的方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57005199/