【发布时间】:2018-06-28 22:10:47
【问题描述】:
我在执行 AspectJ 时遇到了一些问题!
我想为带有@MyAnnotation 注释的方法创建一个日志方法。
MyAnnotation.java:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation{ }
MyAspect.java:
@Aspect
public class MyAspect {
private static Logger logger = Logger.getLogger(MyAspect.class.getName());
@Pointcut("@annotation(com.utils.aop.annotations.MyAnnotation)")
public void logMyAspect() {
}
@Before("logMyAspect()")
public void logMethod(JoinPoint jp) {
String methodName = jp.getSignature().getName();
logger.info("Executing method: " + methodName);
}
}
我在我的项目的一些服务方法之前使用了我的@MyAnnotation:
@RolesAllowed({ "DEV", "GUI", "API" })
@POST
@Path("/getList")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@MyAnnotation
public Response getList(@Context final ContainerRequestContext requestContext,
FilterAndSortObject filterAndSortObject,
@QueryParam("offset") final int offset,
@QueryParam("limit") final int limit)
{
...
}
我还看到我应该在我的配置类中使用@EnableAspectJAutoProxy:
@Configuration
@EnableAspectJAutoProxy
public class ServletContextClass implements ServletContextListener {
final static Logger logger = Logger.getLogger(ServletContextClass.class);
@Override
public void contextInitialized(final ServletContextEvent sce) {
...
}
...
}
但它似乎不起作用。它不记录任何东西!
我在logMethod(JoinPoint jp) 中使用了一个断点并检查了结果,但没有任何成功!
有人知道为什么这不起作用吗?
【问题讨论】:
-
另外请确保您在其中注释方法的类也是 Spring 组件。这在 Spring AOP 中很容易被遗忘。在 AspectJ 中这不是必需的,但 Spring AOP 仅适用于 Spring 管理的 bean。
标签: java spring aspectj spring-aop