I'm trying to understand Spring proxy mechanism and I have problem with one thing. I have Interface:
public interface MyInterface{
void myMethod();
}
and implementing class:
@Component
public class MyBean implements MyInterface{
@Override
public void myMethod(){
//do something
}
}
Now I create Aspect, for example:
@Aspect
@Component
public class LogAspect {
@Before("execution(public * *(..))")
public void logBefore() {
System.out.println("Before aspect");
}
}
And I have simple starter class:
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class SpringAopApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
SpringAopApplication.class);
MyBean bean = ctx.getBean(MyBean.class);
// MyInterface bean = ctx.getBean(MyInterface.class); //works
bean.myMethod();
ctx.close();
}
}
According to the Spring docs we can read:
If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied. If the target object does not implement any interfaces then a CGLIB proxy will be created.
But I got an error No qualifying bean of type [MyBean] is defined. It works only when I enable CGLib proxying by @EnableAspectJAutoProxy(proxyTargetClass = true)
.
Can someone explain what I am missing here? Why MyBean is not discovered when using AOP? ctx.getBean(MyInterface.class)
works, but I can't imagine the situation with many implementations of such interface.