【问题标题】:@EnableAspectJAutoProxy not work with proxyTargetClass=false@EnableAspectJAutoProxy 不适用于 proxyTargetClass=false
【发布时间】:2014-02-26 04:49:44
【问题描述】:

我是第一次学习 Spring AOP。

我正在阅读以下网站: Site2Site1

在此之后,我制作了下一节课

主类:

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)

为什么?

【问题讨论】:

  • MessagePrinter 定义在哪里?

标签: spring-aop spring-annotations


【解决方案1】:
@EnableAspectJAutoProxy(proxyTargetClass=false)

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

@EnableAspectJAutoProxy(proxyTargetClass=true)

相反,使用 CGLIB 代理可以为没有接口的类创建代理。

【讨论】:

    【解决方案2】:

    1> 消息打印机必须定义为一个组件,即: `

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

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

    2> 如果同一类型的 bean 类有许多其他依赖项,则在 spring Config 中解决依赖项使用 @Qualifier 注解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-07
      • 2020-05-21
      • 2019-01-25
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多