Reputation: 73
I'm having some issues with AspectJ implementation!
I want to make a log method for methods with the @MyAnnotation annotation.
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);
}
}
I'm using my @MyAnnotation before some of the service method of my project:
@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)
{
...
}
I've also seen that I should use @EnableAspectJAutoProxy in my configuration class :
@Configuration
@EnableAspectJAutoProxy
public class ServletContextClass implements ServletContextListener {
final static Logger logger = Logger.getLogger(ServletContextClass.class);
@Override
public void contextInitialized(final ServletContextEvent sce) {
...
}
...
}
However it doesn't seem to work. It doesn't log anything!
I used a breakpoint in the logMethod(JoinPoint jp)
as well checking the result, without any success!
Does anyone have any idea why this doesn't work?
Upvotes: 6
Views: 10132
Reputation: 2371
You don't have to separate the pointcut and the handler method; in fact, I'm sure this is what causes your issue. The following aspect should work just fine:
@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);
}
}
You can also inspect your annotation values, in case it takes parameters:
@Before("@annotation(a)")
public void logMyAspect(JoinPoint jp, MyAnnotation a) {
// conditional logging based on annotation contents
}
Upvotes: 5