Search code examples
javaspringspring-mvcaopspring-restcontroller

Spring AOP blocks RestController


I try to learn Spring AOP. I've created simple spring boot project in IDEA.

Service.java

package com.example.demo.service;
//imports..

public interface Service {
    public DataEntity getData();
}

ServiceImpl.java

package com.example.demo.service;
//imports..
@RestController("service")
public class ServiceImpl implements Service {


    @RequestMapping(value="/test", method= RequestMethod.GET)
    public DataEntity getData() {
        DataEntity data = new DataEntity();
        data.setData("SomeString");
        return data;
    }
}

ServiceCallingAspect.java

package com.example.demo.aspects;
//imports..
@Aspect
@EnableAspectJAutoProxy
@Component
public class ServiceCallingAspect {
    private Log log = LogFactory.getLog(ServiceCallingAspect.class);

    @AfterReturning("execution(public * com.example.demo.service.*.*(..))")
    public void logBeforeRestCall(JoinPoint pjp) throws Throwable {
        log.info(" POST REST call " + pjp);
    }
}

DemoApplication.java

package com.example.demo;
//..

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

So when I try to call my rest service on http://localhost:8080/test, I get something like that.

{
    "timestamp": 1514109432038,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/test"
}

When I disable my aspect (just comment all annotations in ServiceCallingAspect.java) the service works perfectly. Can you show me where I am wrong?


Solution

  • Change @EnableAspectJAutoProxy to @EnableAspectJAutoProxy(proxyTargetClass=true).

    @Aspect
    @EnableAspectJAutoProxy(proxyTargetClass=true)
    @Component
    public class ServiceCallingAspect {
      .....
    
    }