我在IDEA中设置了一个新的Spring (不是spring引导),并手动下载aspectjweaver,编写了下面的代码来实践aop。
根配置类是:
@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();
}
}项目布局如下:
+com.dawn.www
-Main.java
+aspect
-Audience.java
+music
-Performance.java
-WoodStock.java我希望Audience是WoodStock的一部分(在春天看到它的行动)
@Aspect
@Component
public class Audience {
@Before("execution(* com.dawn.www.music.Performance.performance(..))")
public void silenceCellPhones(){
System.out.println("-----------Silencing cell phones");
}
}Performance是一个简单的接口,由WoodStock实现。
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,但是当我运行它时:
No qualifying bean of type 'com.dawn.www.music.WoodStock' available 但是当我注释掉@EnableAspectJAutoProxy时,WoodStock可以从应用程序上下文中获取吗?这就是为什么?
发布于 2019-03-01 20:54:15
建议
用“proxyTargetClass=true”和ctx.getBean(WoodStock.class)连用
或
用“proxyTargetClass=false”和ctx.getBean(Performance.class)连用
发布于 2019-03-01 11:25:54
Performance performance=ctx.getBean(Performance.class); Spring只支持接口级代理时,不使用CGLIB,所以不要使用类,使用接口.
https://stackoverflow.com/questions/54943085
复制相似问题