提问者:小点点

@EnableAboojAutoProxy不适用于proxyTargetClass=false


我第一次学习SpringAOP。

我在这个网站上阅读:Site2和Site1

接下来我上了下一节课

主要班级:

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());
    }
}

应用配置类:

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

    @PostConstruct
    public void doAlert() {

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

}

方面类:

@Component
@Aspect
public class AspectMonitor {

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

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

}

而其他人…

就像那个应用程序运行良好一样,但如果我将proxyTargetClass设为false。然后我得到下面的错误。

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)

为什么?


共2个答案

匿名用户

@EnableAspectJAutoProxy(proxyTargetClass=false)

表示将创建JDK动态代理来支持对象上的方面执行。因此,由于这种类型的代理需要一个类来实现一个接口,您的MessagePrinter必须实现一些声明方法getMessage的接口。

@EnableAspectJAutoProxy(proxyTargetClass=true)

相反,指示使用CGLIB代理,它能够为没有接口的类创建代理。

匿名用户

1

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

如果没有为其他包定义@ComponentScan,则在与配置相同的包中java文件。

2