首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@EnableAspectJAutoProxy禁用我的bean定义

@EnableAspectJAutoProxy禁用我的bean定义
EN

Stack Overflow用户
提问于 2019-03-01 10:50:11
回答 2查看 458关注 0票数 0

我在IDEA中设置了一个新的Spring (不是spring引导),并手动下载aspectjweaver,编写了下面的代码来实践aop。

根配置类是:

代码语言:javascript
复制
@Configuration
/*@EnableAspectJAutoProxy*/
@ComponentScan
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext();
        ctx.register(Main.class);
        ctx.refresh();
        Performance performance=ctx.getBean(WoodStock.class);
        //System.out.println(ctx.getBean(Audience.class));
        performance.performance();
     }
}

项目布局如下:

代码语言:javascript
复制
+com.dawn.www
  -Main.java
  +aspect
    -Audience.java
  +music
    -Performance.java
    -WoodStock.java

我希望AudienceWoodStock的一部分(在春天看到它的行动)

代码语言:javascript
复制
@Aspect
@Component
public class Audience {
    @Before("execution(* com.dawn.www.music.Performance.performance(..))")
    public void silenceCellPhones(){
        System.out.println("-----------Silencing cell phones");
    }
}

Performance是一个简单的接口,由WoodStock实现。

代码语言:javascript
复制
public interface Performance {
    void performance();
}

@Component
public class WoodStock implements Performance{
    @Override
    public void performance() {
        System.out.println("WoodStock Performance start,singer singing+++++");
    }
}

@ComponentScan应该找到在应用程序上下文中定义的WoodStockbean,但是当我运行它时:

代码语言:javascript
复制
   No qualifying bean of type 'com.dawn.www.music.WoodStock' available  

但是当我注释掉@EnableAspectJAutoProxy时,WoodStock可以从应用程序上下文中获取吗?这就是为什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-01 20:54:15

  1. 当您使用@EnableAspecjAutoProxy时,spring将自动为所有匹配的bean创建代理(即通过受众方面创建WoodStock )。
  2. 现在,由于您没有在@EnableAspectJAutoProxy上使用“proxyTargetClass=true”,所以它将回到JDK代理而不是CGLIB上。
  3. JDK代理是基于接口的,因此您的代理具有“性能”类型。
  4. 这就是当您尝试使用com.dawn.www.music.WoodStock类型查找bean时,获得“没有”类型为“WoodStock”类型的合格bean的原因。
  5. 现在,在注释了@EnableAspectJAutoProxy之后,WoodStock变成了一个简单的bean,可以通过ctx.getBean(.)访问
  6. 使用'proxyTargetClass=true‘启用CGLIB代理,并创建WoodStock类型的代理

建议

用“proxyTargetClass=true”和ctx.getBean(WoodStock.class)连用

用“proxyTargetClass=false”和ctx.getBean(Performance.class)连用

票数 0
EN

Stack Overflow用户

发布于 2019-03-01 11:25:54

Performance performance=ctx.getBean(Performance.class); Spring只支持接口级代理时,不使用CGLIB,所以不要使用类,使用接口.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54943085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档