Sunday, May 1, 2011

How can I apply an aspect using annotations in Spring?

Update: I've found the Spring 2.x annotation-based Controllers are horrible for AOP security because you can't make assumptions about the method prototype due to the increased freedom in params and return values. Before 2.x you could intercept handleRequest and know the first param was an HttpServletRequest and the return value was a ModelAndView. This standard allowed you to write simple advices for every controller. Now methods mapped to requests can take anything and return Strings, ModelAndViews, etc.

Original Post: I have a set of existing aspects which implement AOPAlliance's MethodInterceptor running in Spring. They provide security for my webapp by intercepting .handleRequest. methods in the Controllers and either allowing execution or forwarding to a login page.

With the new annotation-based controllers in Spring, the "handleRequest" method no longer needs to be implemented; the methods of the controller can be named whatever I want. This breaks my existing security model. So, how do I get from this:

    <bean class="com.xxx.aspects.security.LoginAdvice" name="loginAdvice">
         <property name="loginPath">
              <value>/login.htm</value>
         </property>
         <property name="authenticationService" ref="authenticationService" />
    </bean>

    <bean name="loginAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
         <property name="advice" ref="loginAdvice" />
         <property name="pointcut">
              <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                   <property name="pattern">
                        <value>.*handleRequest.*</value>
                   </property>
              </bean>
         </property>
    </bean>

    <bean id="someProtectedController" class="org.springframework.aop.framework.ProxyFactoryBean">
         <property name="target">
              <ref local="someProtectedControllerTarget" />
         </property>
         <property name="interceptorNames">
              <list>
                   <value>loginAdvisor</value>
                   <value>adminAdvisor</value>
              </list>
         </property>
    </bean>

...to being able to reuse my existing aspects and apply them to entire controllers or controller methods using annotations?

From stackoverflow
  • Could you use an AnnotationMatchingPointcut to look for methods on your controllers which have the @RequestMapping (or other similiar annotations that you use in your annotation-based Spring controllers)?

0 comments:

Post a Comment