spring aop的整体流程思路是这样的:首先先注册一个专门处理aop的BeanPostProcess,在bean的实例化过程中,从BeanPostProcess的list列表中拿出这个处理aop的BeanPostProcess,判断该bean是否满足advise要求,如果符合,会针对该bean创建一个代理对象,最终在ioc容器中,该beanName对应的实例就是这个代理对象。如果不符合,返回的就还是原生对象。
@Configuration
@ComponentScan("com.su.spring.aop")
@EnableAspectJAutoProxy
public class AppConfig {
}
@Component
@org.aspectj.lang.annotation.Aspect
public class Aspect {
@Pointcut("@annotation(com.su.spring.aop.MyAnno)")
public void pointCut(){
System.out.println("point cut");
}
@Before("com.su.spring.aop.Aspect.pointCut()")
public void beforeAdvice(){
System.out.println("before");
}
}
public interface Dao {
String query(String str);
String hello();
}
@Repository("indexDao")
public class IndexDao implements Dao {
@Autowired
TestDao testDao;
@PostConstruct
private void setService(){
System.out.println("-----------");
}
@Override
@MyAnno
public String query(String str) {
System.out.println(str);
return str;
}
@Override
public String hello(){
return "hello";
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnno {
String value() default "";
}
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
Dao dao = (Dao) context.getBean("indexDao");
dao.query("hi");
}
}
执行完AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(AppConfig.class)这一句的时候,就已经完成了代理对象的创建。
接下来就来分析下整个过程吧
aop的入口是从@EnableAspectJAutoProxy这个注解开始的
不管是创建原生对象还是代理对象,肯定都要从bean的实例化开始,关于bean的实例化过程,这里不详细展开,直接从doCreateBean方法开始分析
先来看下AnnotationAwareAspectJAutoProxyCreator的层级结构
最终返回的代理对象是长这样的。