@AspectJ具有特定注释的类的所有方法的切点

2022-08-31 07:39:08

我想监视具有指定注释的所有类的所有公共方法(例如@Monitor)(注意:注释在类级别)。这有什么可能的切入点?注意:我使用的是@AspectJ风格的弹簧AOP。


答案 1

应将文字切入与方法切入相结合。

这些切入点将完成在标有@Monitor注释的类中查找所有公共方法的工作:

@Pointcut("within(@org.rejeev.Monitor *)")
public void beanAnnotatedWithMonitor() {}

@Pointcut("execution(public * *(..))")
public void publicMethod() {}

@Pointcut("publicMethod() && beanAnnotatedWithMonitor()")
public void publicMethodInsideAClassMarkedWithAtMonitor() {}

建议将前两个切入点结合起来的最后一个切入点,你就完成了!

如果您有兴趣,我在这里写了一个具有@AspectJ样式的备忘单,并在此处提供了相应的示例文档


答案 2

使用批注,如问题中所述。

注解:@Monitor

类注释, :app/PagesController.java

package app;
@Controller
@Monitor
public class PagesController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

方法注释:app/PagesController.java

package app;
@Controller
public class PagesController {
    @Monitor
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

自定义注释, :app/Monitor.java

package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}

注释方面:app/MonitorAspect.java

package app;
@Component
@Aspect
public class MonitorAspect {
    @Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void before(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }

    @After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

启用 AspectJ, :servlet-context.xml

<aop:aspectj-autoproxy />

包括AspectJ库, :pom.xml

<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>

推荐