krzakov
krzakov

Reputation: 4121

Spring Aspects (AspectJ) does not seem to work

Well I really don't know why this does not work:

Every jar needed is in the place. Including aspectjrt. Basically I start with configuration class:

@Configuration
@ComponentScan(basePackages = { "some.path" })
@EnableAspectJAutoProxy
public class SomeConf { ... }

Then I have my Aspect:

@Component
@Aspect
public class ControllerLoggerAspect {

    @Pointcut("execution(* some.path.ATest.*(..))")
    private void aspectTest() {
        System.out.println("\n\n ASPECT WORKING \n\n");
    }
}

Under some.path I have Atest class:

package some.path;

public class ATest {

    public void dummyMethod(){
        System.out.println("\n\n\nDummy static executed\n\n\n");
    }
}

Imagine now that I have controller:

@Controller
@RequestMapping(value = "/mapping")
public class SomeController {

    @RequestMapping(value = "/something")
    public ResponseEntity<String> publish(@RequestParam("Id") Long[] ids) {
        //aspect should be invoked here
        new ATest().dummyMethod();

        return new ResponseEntity<>("{ \"status\": \"stubbed\"}", HttpStatus.OK);
    }

}

Everything is invoked properly except aspect method. No errors, no exceptions, nothing. Any ideas?

Upvotes: 1

Views: 902

Answers (2)

kriegaex
kriegaex

Reputation: 67477

Spring AOP only works on Spring beans, i.e. if you want to intercept one of its methods, class ATest needs to be a @Component.

Upvotes: 3

Lorenz Pfisterer
Lorenz Pfisterer

Reputation: 873

You need to configure the advice you want execute. The pointcut only helps in determining the join points. The advice will be executed, not the pointcut.

You could write a Advice like this using your pointcut "aspectTest()":

@Before("aspectTest()")
public void beforeAdvice(){
     System.out.println("\n\n ASPECT WORKING \n\n");
}

Or you could just replace your Pointcut annotation in the example with an advice annotation like this:

@Before("execution(* some.path.ATest.*(..))")
public void aspectTest() {
    System.out.println("\n\n ASPECT WORKING \n\n");
}

Here you have a list of all adivces:

  • @Before("aspectTest()")
  • @After("aspectTest()")
  • @AfterReturning(pointcut = "aspectTest()", returning="retVal")
  • @AfterThrowing(pointcut = "aspectTest()", throwing="ex")
  • @Around("aspectTest()")

Upvotes: 0

Related Questions