Umar Umar - 1 month ago 17
Java Question

Aspect not getting executed

My AspectConfig

@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfig {

@Bean
public SampleRestService restService() {
return new SampleRestService();
}

@Bean
public ServiceMonitor serviceMonitor() {
return new ServiceMonitor();
}
}


My Aspect

@Aspect
@Component
public class ServiceMonitor {

@Pointcut("@annotation(com.web.rest.logging.Monitor)")
public void requestMapping() {}

@Before("requestMapping()")
public void logServiceStart(JoinPoint joinPoint) {
System.out.println("Start: " + joinPoint);
System.out.println(joinPoint.getSignature());
System.out.println(joinPoint.getSignature().getName());
}

}


My Sample Service

@Service
public class SampleRestService {

@Monitor
public static void getParams(){
String url = "<sample url>";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);


HttpEntity entity = new HttpEntity(headers);

RestTemplate restTemplate = new RestTemplate();

ResponseEntity<String> response2 = restTemplate.exchange( url, HttpMethod.GET, entity , String.class );

System.err.println(response2.getBody());

}


My Annotation

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

}


I am calling with this getParams from a Controller which is annotated with @Component

Please let me know if i am missing something,

Do i need to add some more config? or is the pointcut expression wrong.

I have the following jars included

aspectjweaver-1.8.9.jar
aspectjrt-1.8.9.jar
spring-aop-4.2.0.RELEASE.jar

Answer

You're using Spring AOP instead of AspectJ, as indicated by the configuration annotation @EnableAspectJAutoProxy. Spring AOP is not equivalent to AspectJ weaving. Spring AOP works by proxying your spring managed beans, hence it only works on spring beans, with all the limitations of proxy based AOP vs byte-code weaving. Your candidate method getParams is a static method, hence it's not a candidate for Spring AOP. Use either normal AspectJ (compile time weaving or load-time weaving) or remove the static keyword from the method if you intend to stick with Spring AOP. See this answer for further reference.