定义Advice的,表示代理逻辑,以及执行时机:
- @Before
- @AfterReturning
- @AfterThrowing
- @After
- @Around
Spring提供了执行实际的实现类:
- 接口MethodBeforeAdvice,继承了接口BeforeAdvice
- 接口AfterReturningAdvice
- 接口ThrowsAdvice
- 接口AfterAdvice
- 接口MethodInterceptor
Spring会把五个注解解析为对应的Advice类:
- @Before:AspectJMethodBeforeAdvice,实际上就是一个MethodBeforeAdvice
- @AfterReturning:AspectJAfterReturningAdvice,实际上就是一个AfterReturningAdvice
- @AfterThrowing:AspectJAfterThrowingAdvice,实际上就是一个MethodInterceptor
- @After:AspectJAfterAdvice,实际上就是一个MethodInterceptor
- @Around:AspectJAroundAdvice,实际上就是一个MethodInterceptor
TargetSource的使用
在日常的AOP中,被代理对象就是Bean对象,是由BeanFactory给创建出来的,但是Spring AOP中提供了TargetSource机制,可以用来自定义逻辑来创建被代理对象。
比如所提到的@Lazy注解,当加在属性上时,会产生一个代理对象赋值给这个属性,产生代理对象的代码为:
protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, final @Nullable String beanName) { BeanFactory beanFactory = getBeanFactory(); Assert.state(beanFactory instanceof DefaultListableBeanFactory, "BeanFactory needs to be a DefaultListableBeanFactory"); final DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory; TargetSource ts = new TargetSource() { @Override public Class<?> getTargetClass() { return descriptor.getDependencyType(); } @Override public boolean isStatic() { return false; } @Override public Object getTarget() { Set<String> autowiredBeanNames = (beanName != null ? new LinkedHashSet<>(1) : null); Object target = dlbf.doResolveDependency(descriptor, beanName, autowiredBeanNames, null); if (target == null) { Class<?> type = getTargetClass(); if (Map.class == type) { return Collections.emptyMap(); } else if (List.class == type) { return Collections.emptyList(); } else if (Set.class == type || Collection.class == type) { return Collections.emptySet(); } throw new NoSuchBeanDefinitionException(descriptor.getResolvableType(), "Optional dependency not present for lazy injection point"); } if (autowiredBeanNames != null) { for (String autowiredBeanName : autowiredBeanNames) { if (dlbf.containsBean(autowiredBeanName)) { dlbf.registerDependentBean(autowiredBeanName, beanName); } } } return target; } @Override public void releaseTarget(Object target) { } }; ProxyFactory pf = new ProxyFactory(); pf.setTargetSource(ts); Class<?> dependencyType = descriptor.getDependencyType(); if (dependencyType.isInterface()) { pf.addInterface(dependencyType); } return pf.getProxy(dlbf.getBeanClassLoader()); }
这段代码就利用了ProxyFactory来生成代理对象,以及使用了TargetSource,以达到代理对象在执行某个方法时,调用TargetSource的getTarget()方法实时得到一个被代理对象。