Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine @Aspect with @Controller in Spring 3?

I'm trying to setup a Spring 3 Web MVC project, using the @Controller, annotation-based approach.

package my.package

@Controller
@RequestMapping("/admin/*")
public class AdminMultiActionController {

@RequestMapping(value = "admin.htm", method = RequestMethod.GET)
public String showAdminSection() {
    return "admin";
}

My dispatcher-servlet has the following Controller handlers:

<context:component-scan base-package="my.package" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

The webapp is running good with the supplied maven artifacts:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>

Now I wanted to add @AspectJ AOP. I got the libs:

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.9</version>
</dependency>

added to my applicationContext.xml:

<aop:aspectj-autoproxy/>

Made sure to create the relevant bean in the applicationContext.xml as well:

<bean id="securityInterceptor" class="my.package.service.SecurityInterceptor"/>

And started fleshing out the @Aspect:

package my.package.service

@Aspect
public class SecurityInterceptor {

@Pointcut("execution(* showAdminSection(..))")// the pointcut expression
private void foo() {
    System.out.println("fooo");
}// the pointcut signature

Now this is where it stopped working. "fooo" is never printed.

Could it be, because the pointcutted (spelling?) objects must be spring-managed beans and my @Controller in combination with the DefaultAnnotationHandlerMapping is not perceived as such?

Any help would be appreciated. If I forgot to include any information, please ask. Hope someone can help me out here.

Thanks a lot!

like image 698
chzbrgla Avatar asked Oct 21 '10 19:10

chzbrgla


1 Answers

Argh god.. finally got it working!

Thanks for your reply Affe!

For the curious:

  1. Don't use component-scan and defaultannotationhandlers to get your controllers
  2. Wire them in spring xml
  3. Don't have said controllers in dispatcher-servlet whilst aop config sits in applicationContext.
  4. Move both to the dispatcher-servlet

  5. Of course Affe is right: don't forget the advice :p

like image 106
chzbrgla Avatar answered Dec 15 '22 02:12

chzbrgla