Reputation: 8835
I'm trying to create a demo AOP application but it just does not work right.
I read through all tutorials and got it working with @RestController
but as I tried it with a plain java spring driven application I just can't get it to work. Please review my files and tell me where my mistake lies in.
Application Class
@SpringBootApplication
@ComponentScan("com.xetra.experimental")
@EnableAspectJAutoProxy
public class AoptryoutnowebApplication {
public static void main(String[] args) {
SpringApplication.run(AoptryoutnowebApplication.class, args);
DefaultClassToAspectImpl defaultClassToAspectImpl = new DefaultClassToAspectImpl();
defaultClassToAspectImpl.doStuff();
}
}
ClassToAspect Interface
public interface ClassToAspect {
void doStuff();
}
ClassToAspect Implementation
@Component
public class DefaultClassToAspectImpl implements ClassToAspect {
@FooAnnotation
public void doStuff(){
System.out.println("DoStuff!");
}
}
Annotation for Pointcut
public @interface FooAnnotation {
}
Aspect Class
@Aspect
public class FooAspect {
@Pointcut("@annotation(FooAnnotation)")
public void methods(){
}
@Before("methods()")
public void doAspect(){
System.out.println("FooAspect before");
}
}
Upvotes: 0
Views: 64
Reputation: 124536
The problem is you are using a non Spring managed instance by doing new DefaultClassToAspectImpl()
. Spring AOP only works for Spring managed beans, because by default Spring AOP is proxy based.
So instead of doing new DefaultClassToAspectImpl()
you should be obtaining the instance from the ApplicationContext
. When using Spring Boot the SpringApplication.run
call returns an ApplicationContext
. Here you can use one of the getBean
methods to obtain the instance you want.
ApplicationContext ctx = SpringApplication.run(AoptryoutnowebApplication.class, args);
ClassToAspect bean = getBean(ClassToAspect.class);
bean.doStuff();
This way you get the Spring managed
Upvotes: 0
Reputation: 678
Try this:
replace @EnableAspectJAutoProxy
with @EnableAspectJAutoProxy(proxyTargetClass = false)
change pointcut to
@Pointcut("execution (* your.package..*.*(..)) && @annotation(fooAnnotation))")
Upvotes: 1