Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@EnableAspectJAutoProxy not work with proxyTargetClass=false

I am learning about Spring AOP at first time.

I am reading about in this sites: Site2 and Site1

Following this I have made the next classes

Main class:

public class App {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AppConfig.class);
        context.refresh();

        MessagePrinter printer = context.getBean(MessagePrinter.class);

        System.out.println(printer.getMessage());
    }
}

App config class:

@Configuration
@ComponentScan("com.pjcom.springaop")
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AppConfig {

    @PostConstruct
    public void doAlert() {

        System.out.println("Application done.");
    }

}

Aspect class:

@Component
@Aspect
public class AspectMonitor {

    @Before("execution(* com.pjcom.springaop.message.impl.MessagePrinter.getMessage(..))")
    public void beforeMessagePointCut(JoinPoint joinPoint) {

        System.out.println("Monitorizando Mensaje.");
    }

}

And others...

Just like that app work nice, but if I put proxyTargetClass to false. Then I get the error below.

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pjcom.springaop.message.impl.MessagePrinter] is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:318)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:985)
    at com.pjcom.springaop.App.main(App.java:18)

Why?

like image 685
Dani Avatar asked Oct 20 '22 15:10

Dani


1 Answers

@EnableAspectJAutoProxy(proxyTargetClass=false)

Indicates that JDK dynamic proxy will be created to support aspect execution on the object. And therefore as this type of proxy requires a class to implement an interface your MessagePrinter must implement some interface which declares method getMessage.

@EnableAspectJAutoProxy(proxyTargetClass=true)

On the opposite instruct to use CGLIB proxy which is able to create proxy for a class without an interface.

like image 80
polbotinka Avatar answered Oct 24 '22 00:10

polbotinka