框架就是复杂的留给自己,简单的留给码农,像写hello world一样简单
例如:
它这种配置是如何解析的,拦截方法怎么拿到,注入到代理,代理对象如何生成,
看下文,可以先参考我的博文bean创建过程一个Spring Bean从无到有的过程,
xml元素解析就不具体说了,感兴趣自己研究
由于我用的tag是
然后解析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.
* 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 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;
}
在创建代理对象前,会拿到通知或拦截方法
/**
* 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.
* Can be called repeatedly. Effect will vary if we've added
* or removed interfaces. Can add and remove interceptors.
*
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 not
* 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
/**
* JDK-based {@link AopProxy} implementation for the Spring AOP framework,
* based on JDK {@link java.lang.reflect.Proxy dynamic proxies}.
*
* Creates a dynamic proxy, implementing the interfaces exposed by
* the AopProxy. Dynamic proxies cannot be used to proxy methods
* defined in classes, rather than interfaces.
*
*
Objects of this type should be obtained through proxy factories,
* configured by an {@link AdvisedSupport} class. This class is internal
* to Spring's AOP framework and need not be used directly by client code.
*
*
Proxies created using this class will be thread-safe if the
* underlying (target) class is thread-safe.
*
*
Proxies are serializable so long as all Advisors (including Advices
* and Pointcuts) and the TargetSource are serializable.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Rob Harrop
* @author Dave Syer
* @see java.lang.reflect.Proxy
* @see AdvisedSupport
* @see ProxyFactory
*/
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
/** Config used to configure this proxy */
private final AdvisedSupport advised;
/**
* Construct a new JdkDynamicAopProxy for the given AOP configuration.
* @param config the AOP configuration as AdvisedSupport object
* @throws AopConfigException if the config is invalid. We try to throw an informative
* exception in this case, rather than let a mysterious failure happen later.
*/
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
Assert.notNull(config, "AdvisedSupport must not be null");
if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
throw new AopConfigException("No advisors and no TargetSource specified");
}
this.advised = config;
}
@Override
public Object getProxy() {
return getProxy(ClassUtils.getDefaultClassLoader());
}
@Override
public Object getProxy(ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
}
Class>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
//jdk自带的工具
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
/**
* Implementation of {@code InvocationHandler.invoke}.
*
Callers will see exactly the exception thrown by the target,
* unless a hook method throws an exception.
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Class> targetClass = null;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// May be null. Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
//得到目标对象
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}
// Get the interception chain for this method.
// 得到定义好的拦截器链
List
此时已是代理对象
然后一层层返回:
代理对象执行业务方法,顺便加些其他操作
附图两张:
参考:
0. https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#xsd-schemas-aop
1. https://www.springframework.org/schema/aop/spring-aop.xsd
2. http://www.docjar.com/html/api/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java.html
3. https://github.com/seaswalker/spring-analysis/blob/master/note/spring-aop.md
4. Spring 框架的设计理念与设计模式分析 https://www.ibm.com/developerworks/cn/java/j-lo-spring-principle/index.html
6. Spring 源码学习(八) AOP 使用和实现原理
http://www.justdojava.com/2019/07/17/spring-analysis-note-8/
7. Spring AOP 源码初窥(三)扫描Advice与Bean匹配 https://segmentfault.com/a/1190000016054658
9. spring源码解析之AOP原理 https://www.cnblogs.com/liuyk-code/p/9886033.html
https://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations