@EnableAspectJAutoProxy not work with proxyTargetClass=false

北城以北 提交于 2020-01-02 05:38:12

问题


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?


回答1:


@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.




回答2:


1> Message Printer has to be defined as a component i.e : `

 package com.pjcom.springaop.message.impl;
    @Component
    public class MessagePrinter{
    public void getMessage(){
    System.out.println("getMessage() called");
    }
    }`

in the same package as configuration java file if no @ComponentScan is not defined for some other packages.

2> If same type of bean class has many other dependencies then to resolve dependencies in spring Config use @Qualifier annotation.



来源:https://stackoverflow.com/questions/21514858/enableaspectjautoproxy-not-work-with-proxytargetclass-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!