【问题标题】:Spring AOP blocks RestControllerSpring AOP 阻塞 RestController
【发布时间】:2017-12-24 19:57:41
【问题描述】:

我尝试学习 Spring AOP。我在 IDEA 中创建了简单的 Spring Boot 项目。

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);
    }
}

所以当我尝试在 http://localhost:8080/test 上调用我的休息服务时,我得到了类似的信息。

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

当我禁用我的方面(只需评论 ServiceCallingAspect.java 中的所有注释)时,该服务可以完美运行。你能告诉我哪里错了吗?

【问题讨论】:

  • 当您尝试访问 url 时,它是否会影响控制器?你调试过这个吗?
  • @pvpkiran 否,在调试模式下无法访问控制器。

标签: java spring spring-mvc aop spring-restcontroller


【解决方案1】:

@EnableAspectJAutoProxy 更改为@EnableAspectJAutoProxy(proxyTargetClass=true)

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

}

【讨论】:

  • 这很好用,谢谢!你能解释一下它是如何工作的吗?
猜你喜欢
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 2022-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多