我在IDEA中设置了一个新的Spring App(而不是spring boot),并手动下载了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
应该找到在应用程序上下文中定义的WoodStock
bean,但是当我运行它时:
No qualifying bean of type 'com.dawn.www.music.WoodStock' available
但是当我评论出@EnableAspectJAutoProxy
时,WoodStock可以从应用程序环境中获取?这就是为什么?
建议
使用'proxyTargetClass = true'和ctx.getBean(WoodStock.class)
要么
将'proxyTargetClass = false'与ctx.getBean(Performance.class)一起使用
Performance performance=ctx.getBean(Performance.class);
Spring Aop仅在不使用CGLIB时支持接口级代理,因此不要使用类,使用接口。