代码之家  ›  专栏  ›  技术社区  ›  BZHNomad

AspectJ@在注释问题之前

  •  4
  • BZHNomad  · 技术社区  · 8 年前

    我在AspectJ实现方面遇到了一些问题!
    我想为带有@MyAnnotation注释的方法创建一个log方法。

    MyAnnotation。java:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface MyAnnotation{ }
    

    我的方面。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) 以及检查结果,没有任何成功!

    有人知道为什么这样不行吗?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Alex Savitsky    8 年前

    您不必分离切入点和处理程序方法;事实上,我相信这就是你的问题所在。以下方面应该可以正常工作:

    @Aspect
    public class MyAspect {
        private static Logger logger = Logger.getLogger(MyAspect.class.getName());
        @Before("@annotation(com.utils.aop.annotations.MyAnnotation)")
        public void logMyAspect(JoinPoint jp) {
            String methodName = jp.getSignature().getName();
            logger.info("Executing method: " + methodName);
        }
    }
    

    如果注释值采用参数,也可以检查注释值:

    @Before("@annotation(a)")
    public void logMyAspect(JoinPoint jp, MyAnnotation a) {
        // conditional logging based on annotation contents
    }