BZH*_*mad 5 java spring aspectj spring-aop
我在 AspectJ 实现方面遇到一些问题!
我想为带有 @MyAnnotation 注释的方法创建一个日志方法。
MyAnnotation.java:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation{ }
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我在项目的一些服务方法之前使用我的@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)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我还发现我应该在配置类中使用 @EnableAspectJAutoProxy :
@Configuration
@EnableAspectJAutoProxy
public class ServletContextClass implements ServletContextListener {
final static Logger logger = Logger.getLogger(ServletContextClass.class);
@Override
public void contextInitialized(final ServletContextEvent sce) {
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
然而它似乎不起作用。它不记录任何内容!
我在检查结果时也使用了断点logMethod(JoinPoint jp),但没有成功!
有谁知道为什么这不起作用?
您不必将切入点和处理程序方法分开;事实上,我确信这就是导致您出现问题的原因。以下方面应该可以正常工作:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以检查注释值,以防它带有参数:
@Before("@annotation(a)")
public void logMyAspect(JoinPoint jp, MyAnnotation a) {
// conditional logging based on annotation contents
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7486 次 |
| 最近记录: |