框架就是複雜的留給自己,簡單的留給碼農,像寫hello world一樣簡單 早年開發Spring AOP程式時,都是xml文件配置aop(現在不流行xml了,註解@EnableAspectJAutoProxy大行其道),然後框架解析, 例如: 它這種配置是如何解析的,攔截方法怎麼拿到,註入到代理, ...
框架就是複雜的留給自己,簡單的留給碼農,像寫hello world一樣簡單
早年開發Spring AOP程式時,都是xml文件配置aop(現在不流行xml了,註解@EnableAspectJAutoProxy大行其道),然後框架解析,
例如:
看下文,可以先參考我的博文bean創建過程一個Spring Bean從無到有的過程,
xml元素解析就不具體說了,感興趣自己研究
由於我用的tag是<aop:config>,那麼解析類就是ConfigBeanDefinitionParser,解析時會註冊一個AspectJAwareAdvisorAutoProxyCreator,一個高高高級的BeanPostProcessor
然後解析aop:config子元素,由於方法眾多,我只寫了大塊
if (POINTCUT.equals(localName)) {
parsePointcut(elt, parserContext);
}
else if (ADVISOR.equals(localName)) {
parseAdvisor(elt, parserContext);
}
else if (ASPECT.equals(localName)) {
parseAspect(elt, parserContext);
}
參照https://blog.csdn.net/dong19891210/article/details/105697175創建bean的createBeanInstance(產出原生對象)和initializeBean階段,對應文件org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
//.......略
if (mbd == null || !mbd.isSynthetic()) {
System.out.println(beanName+" AOP 6666666666666666");
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
System.out.println(wrappedBean.getClass()+" AOP 888888888888");
}
return wrappedBean;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
System.out.println("對象:"+existingBean+" 的類型是:"+existingBean.getClass());
List<BeanPostProcessor> beanPostProcessorList = getBeanPostProcessors();
System.out.println("BeanPostProcessor列表: "+beanPostProcessorList);
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
//Bean初始化之後
System.out.println(beanProcessor.getClass().getName());
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
在for之前輸出:
calculator AOP 6666666666666666
對象:spring.aop.CalculatorImp@906d29b 的類型是:class spring.aop.CalculatorImp
BeanPostProcessor列表: [org.springframework.context.support.ApplicationContextAwareProcessor@49d3c823, org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker@436bc36, org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor@3b8f0a79, org.springframework.context.annotation.ConfigurationClassPostProcessor$EnhancedConfigurationBeanPostProcessor@71e693fa, proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false, org.springframework.context.annotation.CommonAnnotationBeanPostProcessor@4f6f416f, org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor@409c54f, org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor@3e74829, org.springframework.context.support.PostProcessorRegistrationDelegate$ApplicationListenerDetector@5fe1ce85]
獲取所有的BeanPostProcessor,
進入for階段後,留意一個org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator 的處理
處理方式可以細看,由於代碼超多,只展示大方面的代碼
還記得上面說過的註冊的一個bean:AspectJAwareAdvisorAutoProxyCreator,它繼承自org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(Object bean, String beanName) throws BeansException
/**
* Create a proxy with the configured interceptors if the bean is
* identified as one to proxy by the subclass.
* @see #getAdvicesAndAdvisorsForBean
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
//
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
/**
* Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
* @param bean the raw bean instance
* @param beanName the name of the bean
* @param cacheKey the cache key for metadata access
* @return a proxy wrapping the bean, or the raw bean instance as-is
*/
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
//。。。。。略
// Create proxy if we have advice.預備創建代理對象,拿到攔截方法
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
System.out.println("org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(Object bean, String beanName) ");
this.advisedBeans.put(cacheKey, Boolean.TRUE);
//spring aop產生“代理對象”的地方
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
在創建代理對象前,會拿到通知或攔截方法
1. 拿攔截方式org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource)
2. 創建代理 Object org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource)
/**
* Create an AOP proxy for the given bean.
* @param beanClass the class of the bean
* @param beanName the name of the bean
* @param specificInterceptors the set of interceptors that is
* specific to this bean (may be empty, but not null)
* @param targetSource the TargetSource for the proxy,
* already pre-configured to access the bean
* @return the AOP proxy for the bean
* @see #buildAdvisors
*/
protected Object createProxy(
Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}
//開始準備原料
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
if (!proxyFactory.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
//很重要
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
for (Advisor advisor : advisors) {
proxyFactory.addAdvisor(advisor);
}
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
//創建代理
return proxyFactory.getProxy(getProxyClassLoader());
}
文件org.springframework.aop.framework.proxyFactory.java
/**
* Create a new proxy according to the settings in this factory.
* <p>Can be called repeatedly. Effect will vary if we've added
* or removed interfaces. Can add and remove interceptors.
* <p>Uses the given class loader (if necessary for proxy creation).
* @param classLoader the class loader to create the proxy with
* (or {@code null} for the low-level proxy facility's default)
* @return the proxy object
*/
public Object getProxy(ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
public class ProxyCreatorSupport extends AdvisedSupport {
//。。。略
/**
* Create a new ProxyCreatorSupport instance.
*/
public ProxyCreatorSupport() {
this.aopProxyFactory = new DefaultAopProxyFactory();
}
/**
* Return the AopProxyFactory that this ProxyConfig uses.
*/
public AopProxyFactory getAopProxyFactory() {
return this.aopProxyFactory;
}
/**
* Subclasses should call this to get a new AOP proxy. They should <b>not</b>
* create an AOP proxy with {@code this} as an argument.
*/
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
}
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
//如果targetClass是介面,則使用JDK生成代理proxy
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
//若不是介面,則使用cglib生成代理類proxy
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
}
由於我用的是介面,那麼代理實現類是JdkDynamicAopProxy.java