implement AOP for Controllers in Spring 3

后端 未结 2 1579
一个人的身影
一个人的身影 2021-01-01 07:50

How do I implement AOP with an annotated Controller?

I\'ve search and found two previous posts regarding the problem, but can\'t seem to get the solutions to work.

相关标签:
2条回答
  • 2021-01-01 08:28

    I am going to state an alternative solution (sorry not a direct answer) but what you wanting to do is probably best done via interceptors and filters.

    0 讨论(0)
  • 2021-01-01 08:41

    In order to put an aspect on a HandlerMethod in a class annotated with @Controller in Spring 3.1 you need to have the proxy-target-class="true" attribute on the aspectj-autoproxy element. You also need to have the CGLIB and the ASM libraries as a dependency in your WAR/EAR file. You can either specify your annotated aspect class as a bean and use the aop:include as stated above or you can leave the aop:include out and add a filter similar to this in your component scan element:

    <context:component-scan>
      <context:include-filter type="aspectj"
        expression="com.your.aspect.class.Here"/>
    </context:component-scan>
    

    I do not know if this is a requirement as a result of Spring 3.1 only but I know that without this, you will not be able to put an aspect on your controller HandlerMethod. You would get an error similar to:

    Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
    HandlerMethod details: 
    Controller [$Proxy82]
    Method [public void com.test.TestController.testMethod(java.security.Principal,javax.servlet.http.HttpServletResponse) throws javax.servlet.ServletException]
    Resolved arguments: 
    [0] [null] 
    [1] [type=com.ibm.ws.webcontainer.srt.SRTServletResponse] [value=com.ibm.ws.webcontainer.srt.SRTServletResponse@dcd0dcd]
    

    This is not required if your aspect is on a method in a class that is not a controller

    0 讨论(0)
提交回复
热议问题