Dan*_*ani 5 spring-aop spring-annotations
我是第一次学习 Spring AOP。
在此之后,我做了下一个课程
主要类:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
应用配置类:
@Configuration
@ComponentScan("com.pjcom.springaop")
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AppConfig {
@PostConstruct
public void doAlert() {
System.out.println("Application done.");
}
}
Run Code Online (Sandbox Code Playgroud)
方面类:
@Component
@Aspect
public class AspectMonitor {
@Before("execution(* com.pjcom.springaop.message.impl.MessagePrinter.getMessage(..))")
public void beforeMessagePointCut(JoinPoint joinPoint) {
System.out.println("Monitorizando Mensaje.");
}
}
Run Code Online (Sandbox Code Playgroud)
和别的...
就像那个应用程序运行良好一样,但是如果我将 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)
Run Code Online (Sandbox Code Playgroud)
为什么?
小智 4
@EnableAspectJAutoProxy(proxyTargetClass=false)
Run Code Online (Sandbox Code Playgroud)
指示将创建 JDK 动态代理来支持对象上的切面执行。因此,由于这种类型的代理需要一个类来实现接口,因此您MessagePrinter必须实现一些声明方法的接口getMessage。
@EnableAspectJAutoProxy(proxyTargetClass=true)
Run Code Online (Sandbox Code Playgroud)
相反,指示使用 CGLIB 代理,它能够为没有接口的类创建代理。