我已经为aop做了注解。当我在任何方法而不是 Controller 方法中使用它时,它都能很好地工作。但是,当我在 Controller 的方法中使用它时,我的 Controller 停止工作。它开始为映射提供 404 未找到错误。我在这里发现了一个类似的问题:Spring 3 MVC @Controller with AOP interceptors?但我不知道该怎么做。我在我的 Controller 上的方法是:
@WebAuditable // This is my annotation that works at other methods
@Override
@RequestMapping(value = "/ad", method = RequestMethod.POST, headers = "Accept=application/json")
public
@ResponseBody
Cd create(HttpServletResponse response, @RequestBody Cd cd) {
...
}
我的 Controller 实现的接口(interface)是:
public interface BaseController<T> {
public List<T> getAll(HttpServletResponse response);
public T getByName(HttpServletResponse response, String id);
public T create(HttpServletResponse response, T t);
public T update(HttpServletResponse response, T t);
}
有什么建议吗?
PS: @SeanPatrickFloyd 说:
Note When using controller interfaces (e.g. for AOP proxying), make sure to consistently put all your mapping annotations - such as @RequestMapping and @SessionAttributes - on the controller interface rather than on the implementation class
最佳答案
问题是: Controller 映射是在运行时完成的,如果您使用 AOP 代理,则代理对象在运行时没有注释,只有它们的接口(interface)有。我可以想到两种可能的策略来解决此限制。
要么注释通用接口(interface)方法,要么(如果您不想通知所有 Controller )为每个实现类型创建一个子接口(interface),显式注释它们的方法。我知道有很多重写的代码并且与 AOP 的内容相反,但是我不知道坚持使用基于接口(interface)的代理时有什么更好的方法。
另一种方法是使用 proxy-target-class="true"切换到 CGLib 代理。这样代理类应该(我不确定)保留注释。
更新:注释你的界面应该像这样工作(如果它有效的话)
public interface BaseController<T> {
@WebAuditable
public List<T> getAll(HttpServletResponse response);
@WebAuditable
public T getByName(HttpServletResponse response, String id);
@WebAuditable
public T create(HttpServletResponse response, T t);
@WebAuditable
public T update(HttpServletResponse response, T t);
}
注释基类是行不通的,因为 JDK 代理不会公开任何不受接口(interface)支持的信息。
关于java - Spring Controller 的 Aop 注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8234059/