AOP 代理類的創建
阿新 • • 發佈:2019-01-28
nap bili creat aop static aware truct rop pda
AOP 代理類的創建
入口:AnnotationAwareAspectJAutoProxyCreator#postProcessAfterInitialization 和 AnnotationAwareAspectJAutoProxyCreator#getEarlyBeanReference
/** * 代理配置:保證所有的代理創建者都有一致的屬性配置 */ public class ProxyConfig implements Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ private static final long serialVersionUID = -8409359707199703185L; /** * 是否是基於類的代理,默認是基於接口的代理 */ private boolean proxyTargetClass = false; /** * 是否執行代理優化,【如果為 true,在代理創建完畢後,修改通知將沒有效果】 */ private boolean optimize = false; /** * 是否不允許將代理類強轉為 Advised,默認可以 */ boolean opaque = false; /** * 代理類是否需要暴露到 AopContext 的 currentProxy 中 */ boolean exposeProxy = false; /** * 是否凍結代理配置,凍結後不可修改 */ private boolean frozen = false; public void setProxyTargetClass(boolean proxyTargetClass) { this.proxyTargetClass = proxyTargetClass; } public boolean isProxyTargetClass() { return proxyTargetClass; } public void setOptimize(boolean optimize) { this.optimize = optimize; } public boolean isOptimize() { return optimize; } public void setOpaque(boolean opaque) { this.opaque = opaque; } public boolean isOpaque() { return opaque; } public void setExposeProxy(boolean exposeProxy) { this.exposeProxy = exposeProxy; } public boolean isExposeProxy() { return exposeProxy; } public void setFrozen(boolean frozen) { this.frozen = frozen; } public boolean isFrozen() { return frozen; } /** * 從另一個 ProxyConfig 中復制屬性 */ public void copyFrom(ProxyConfig other) { Assert.notNull(other, "Other ProxyConfig object must not be null"); proxyTargetClass = other.proxyTargetClass; optimize = other.optimize; exposeProxy = other.exposeProxy; frozen = other.frozen; opaque = other.opaque; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("proxyTargetClass=").append(proxyTargetClass).append("; "); sb.append("optimize=").append(optimize).append("; "); sb.append("opaque=").append(opaque).append("; "); sb.append("exposeProxy=").append(exposeProxy).append("; "); sb.append("frozen=").append(frozen); return sb.toString(); } } /** * 具有代理處理器通用功能的基類 */ @SuppressWarnings("serial") public class ProxyProcessorSupport extends ProxyConfig implements Ordered, BeanClassLoaderAware, AopInfrastructureBean { /** * 它應該在其他所有處理器之後運行 */ private int order = Ordered.LOWEST_PRECEDENCE; @Nullable private ClassLoader proxyClassLoader = ClassUtils.getDefaultClassLoader(); private boolean classLoaderConfigured = false; public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return order; } public void setProxyClassLoader(@Nullable ClassLoader classLoader) { proxyClassLoader = classLoader; classLoaderConfigured = classLoader != null; } @Nullable protected ClassLoader getProxyClassLoader() { return proxyClassLoader; } @Override public void setBeanClassLoader(ClassLoader classLoader) { if (!classLoaderConfigured) { proxyClassLoader = classLoader; } } /** * 嘗試將目標類型實現的所有接口添加到 proxyFactory 中 */ protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) { // 獲取目標類型的所有接口 final Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader()); boolean hasReasonableProxyInterface = false; for (final Class<?> ifc : targetInterfaces) { // 目標接口不是回調接口和內部語言接口 && 接口中存在方法,則需要為其創建代理 if (!isConfigurationCallbackInterface(ifc) && !isInternalLanguageInterface(ifc) && ifc.getMethods().length > 0) { hasReasonableProxyInterface = true; break; } } if (hasReasonableProxyInterface) { /** * 此處還需要設置引入接口,以實現切面引入接口功能 */ for (final Class<?> ifc : targetInterfaces) { proxyFactory.addInterface(ifc); } } else { // 無需要代理的接口,則直接創建基於類的代理 proxyFactory.setProxyTargetClass(true); } } /** * 目標接口是容器回調接口 * InitializingBean * DisposableBean * Closeable * AutoCloseable * Aware */ protected boolean isConfigurationCallbackInterface(Class<?> ifc) { // 可改成 Aware.class.isAssignableFrom(ifc); return InitializingBean.class == ifc || DisposableBean.class == ifc || Closeable.class == ifc || AutoCloseable.class == ifc || ObjectUtils.containsElement(ifc.getInterfaces(), Aware.class); } /** * 目標接口是內部語言接口 */ protected boolean isInternalLanguageInterface(Class<?> ifc) { return ifc.getName().equals("groovy.lang.GroovyObject") || ifc.getName().endsWith(".cglib.proxy.Factory") || ifc.getName().endsWith(".bytebuddy.MockAccess"); } } /** * BeanPostProcessor 接口實現類,嘗試基於目標對象創建代理類。 */ @SuppressWarnings("serial") public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware { /** * 無需代理 */ @Nullable protected static final Object[] DO_NOT_PROXY = null; /** * 無需應用擴展的 interceptors */ protected static final Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0]; protected final Log logger = LogFactory.getLog(getClass()); /** Default is global AdvisorAdapterRegistry. */ private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); /** * 是否需要凍結代理 */ private boolean freezeProxy = false; /** Default is no common interceptors. */ private String[] interceptorNames = new String[0]; private boolean applyCommonInterceptorsFirst = true; @Nullable private TargetSourceCreator[] customTargetSourceCreators; @Nullable private BeanFactory beanFactory; private final Set<String> targetSourcedBeans = Collections.newSetFromMap(new ConcurrentHashMap<>(16)); private final Set<Object> earlyProxyReferences = Collections.newSetFromMap(new ConcurrentHashMap<>(16)); private final Map<Object, Class<?>> proxyTypes = new ConcurrentHashMap<>(16); /** * 已經處理的 Bean 緩存 */ private final Map<Object, Boolean> advisedBeans = new ConcurrentHashMap<>(256); @Override public void setFrozen(boolean frozen) { freezeProxy = frozen; } @Override public boolean isFrozen() { return freezeProxy; } public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) { this.advisorAdapterRegistry = advisorAdapterRegistry; } public void setCustomTargetSourceCreators(TargetSourceCreator... targetSourceCreators) { customTargetSourceCreators = targetSourceCreators; } public void setInterceptorNames(String... interceptorNames) { this.interceptorNames = interceptorNames; } public void setApplyCommonInterceptorsFirst(boolean applyCommonInterceptorsFirst) { this.applyCommonInterceptorsFirst = applyCommonInterceptorsFirst; } @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } @Nullable protected BeanFactory getBeanFactory() { return beanFactory; } @Override @Nullable public Class<?> predictBeanType(Class<?> beanClass, String beanName) { if (proxyTypes.isEmpty()) { return null; } final Object cacheKey = getCacheKey(beanClass, beanName); return proxyTypes.get(cacheKey); } @Override @Nullable public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) { return null; } @Override public Object getEarlyBeanReference(Object bean, String beanName) { final Object cacheKey = getCacheKey(bean.getClass(), beanName); if (!earlyProxyReferences.contains(cacheKey)) { earlyProxyReferences.add(cacheKey); } return wrapIfNecessary(bean, beanName, cacheKey); } /** * 實例化之前的後處理 */ @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) { final Object cacheKey = getCacheKey(beanClass, beanName); if (!StringUtils.hasLength(beanName) || !targetSourcedBeans.contains(beanName)) { if (advisedBeans.containsKey(cacheKey)) { return null; } if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { advisedBeans.put(cacheKey, Boolean.FALSE); return null; } } // Create proxy here if we have a custom TargetSource. final TargetSource targetSource = getCustomTargetSource(beanClass, beanName); if (targetSource != null) { if (StringUtils.hasLength(beanName)) { targetSourcedBeans.add(beanName); } final Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource); final Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource); proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } return null; } @Override public boolean postProcessAfterInstantiation(Object bean, String beanName) { return true; } @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { return pvs; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } /** * 嘗試為目標 bean 創建代理 */ @Override public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) { if (bean != null) { final Object cacheKey = getCacheKey(bean.getClass(), beanName); if (!earlyProxyReferences.contains(cacheKey)) { return wrapIfNecessary(bean, beanName, cacheKey); } } return bean; } protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) { if (StringUtils.hasLength(beanName)) { return FactoryBean.class.isAssignableFrom(beanClass) ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName; } else { return beanClass; } } protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { // 排除 targetSource Bean if (StringUtils.hasLength(beanName) && targetSourcedBeans.contains(beanName)) { return bean; } // 排除 advisedBean if (Boolean.FALSE.equals(advisedBeans.get(cacheKey))) { return bean; } /** * 排除基礎設施 Bean 和 * bean 名稱以全類名開頭 && 以 AutowireCapableBeanFactory.ORIGINAL_INSTANCE_SUFFIX 結尾的 Bean */ if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } // 如果我們有通知,則創建代理類 final Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); if (specificInterceptors != DO_NOT_PROXY) { advisedBeans.put(cacheKey, Boolean.TRUE); final Object proxy = createProxy( bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } /** * 是否是基礎設施 Bean */ protected boolean isInfrastructureClass(Class<?> beanClass) { final boolean retVal = Advice.class.isAssignableFrom(beanClass) || Pointcut.class.isAssignableFrom(beanClass) || Advisor.class.isAssignableFrom(beanClass) || AopInfrastructureBean.class.isAssignableFrom(beanClass); if (retVal && logger.isTraceEnabled()) { logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]"); } return retVal; } protected boolean shouldSkip(Class<?> beanClass, String beanName) { return AutoProxyUtils.isOriginalInstance(beanName, beanClass); } /** * Create a target source for bean instances. */ @Nullable protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) { // 不能為直接創建的單例對象創建目標源 if (customTargetSourceCreators != null && beanFactory != null && beanFactory.containsBean(beanName)) { for (final TargetSourceCreator tsc : customTargetSourceCreators) { final TargetSource ts = tsc.getTargetSource(beanClass, beanName); if (ts != null) { // Found a matching TargetSource. if (logger.isTraceEnabled()) { logger.trace("TargetSourceCreator [" + tsc + "] found custom TargetSource for bean with name ‘" + beanName + "‘"); } return ts; } } } // No custom TargetSource found. return null; } /** * 為指定的 bean 創建代理 */ protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) { if (beanFactory instanceof ConfigurableListableBeanFactory) { AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) beanFactory, beanName, beanClass); } // 創建代理工廠 final ProxyFactory proxyFactory = new ProxyFactory(); // 復制代理屬性 proxyFactory.copyFrom(this); // 1)如果是基於接口的代理 if (!proxyFactory.isProxyTargetClass()) { // 2)是否應該轉換為類代理 if (shouldProxyTargetClass(beanClass, beanName)) { proxyFactory.setProxyTargetClass(true); } else { // 計算需要代理的接口 evaluateProxyInterfaces(beanClass, proxyFactory); } } // 創建 Advisor final Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); proxyFactory.addAdvisors(advisors); proxyFactory.setTargetSource(targetSource); // 自定義鉤子 customizeProxyFactory(proxyFactory); proxyFactory.setFrozen(freezeProxy); if (advisorsPreFiltered()) { proxyFactory.setPreFiltered(true); } // 基於 ProxyFactory 創建代理類 return proxyFactory.getProxy(getProxyClassLoader()); } protected boolean shouldProxyTargetClass(Class<?> beanClass, @Nullable String beanName) { return beanFactory instanceof ConfigurableListableBeanFactory && AutoProxyUtils.shouldProxyTargetClass((ConfigurableListableBeanFactory) beanFactory, beanName); } protected boolean advisorsPreFiltered() { return false; } protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) { // Handle prototypes correctly... final Advisor[] commonInterceptors = resolveInterceptorNames(); final List<Object> allInterceptors = new ArrayList<>(); if (specificInterceptors != null) { allInterceptors.addAll(Arrays.asList(specificInterceptors)); if (commonInterceptors.length > 0) { if (applyCommonInterceptorsFirst) { allInterceptors.addAll(0, Arrays.asList(commonInterceptors)); } else { allInterceptors.addAll(Arrays.asList(commonInterceptors)); } } } if (logger.isTraceEnabled()) { final int nrOfCommonInterceptors = commonInterceptors.length; final int nrOfSpecificInterceptors = specificInterceptors != null ? specificInterceptors.length : 0; logger.trace("Creating implicit proxy for bean ‘" + beanName + "‘ with " + nrOfCommonInterceptors + " common interceptors and " + nrOfSpecificInterceptors + " specific interceptors"); } final Advisor[] advisors = new Advisor[allInterceptors.size()]; for (int i = 0; i < allInterceptors.size(); i++) { advisors[i] = advisorAdapterRegistry.wrap(allInterceptors.get(i)); } return advisors; } /** * Resolves the specified interceptor names to Advisor objects. */ private Advisor[] resolveInterceptorNames() { final BeanFactory bf = beanFactory; final ConfigurableBeanFactory cbf = bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null; final List<Advisor> advisors = new ArrayList<>(); for (final String beanName : interceptorNames) { if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) { Assert.state(bf != null, "BeanFactory required for resolving interceptor names"); final Object next = bf.getBean(beanName); advisors.add(advisorAdapterRegistry.wrap(next)); } } return advisors.toArray(new Advisor[0]); } /** * Subclasses may choose to implement this: for example, * to change the interfaces exposed. */ protected void customizeProxyFactory(ProxyFactory proxyFactory) { } /** * 讀取指定類的 Advisors */ @Nullable protected abstract Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource customTargetSource) throws BeansException; } /** * 為特定的 bean 構建 AOP 代理類 */ @SuppressWarnings("serial") public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator { /** * 用於從 BeanFactory 中獲取標準的 Advisors */ @Nullable private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper; @Override public void setBeanFactory(BeanFactory beanFactory) { super.setBeanFactory(beanFactory); if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { throw new IllegalArgumentException( "AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory); } initBeanFactory((ConfigurableListableBeanFactory) beanFactory); } protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) { advisorRetrievalHelper = new BeanFactoryAdvisorRetrievalHelperAdapter(beanFactory); } @Override @Nullable protected Object[] getAdvicesAndAdvisorsForBean( Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) { final List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName); if (advisors.isEmpty()) { return DO_NOT_PROXY; } return advisors.toArray(); } /** * 查找能自動代理此類的所有 Advisor */ protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) { final List<Advisor> candidateAdvisors = findCandidateAdvisors(); // 查找能夠應用到此類的所有 Advisor List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); extendAdvisors(eligibleAdvisors); if (!eligibleAdvisors.isEmpty()) { // 排序 eligibleAdvisors = sortAdvisors(eligibleAdvisors); } return eligibleAdvisors; } protected List<Advisor> findCandidateAdvisors() { Assert.state(advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available"); return advisorRetrievalHelper.findAdvisorBeans(); } /** * 從候選的 Advisors 列表中,查找能夠應用通知到此類的所有 Advisors */ protected List<Advisor> findAdvisorsThatCanApply( List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) { ProxyCreationContext.setCurrentProxiedBeanName(beanName); try { return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); } finally { ProxyCreationContext.setCurrentProxiedBeanName(null); } } protected boolean isEligibleAdvisorBean(String beanName) { return true; } protected List<Advisor> sortAdvisors(List<Advisor> advisors) { // 根據 @Order 進行排序 AnnotationAwareOrderComparator.sort(advisors); return advisors; } /** * 允許子類定制化的擴展接口 */ protected void extendAdvisors(List<Advisor> candidateAdvisors) { } @Override protected boolean advisorsPreFiltered() { return true; } private class BeanFactoryAdvisorRetrievalHelperAdapter extends BeanFactoryAdvisorRetrievalHelper { public BeanFactoryAdvisorRetrievalHelperAdapter(ConfigurableListableBeanFactory beanFactory) { super(beanFactory); } @Override protected boolean isEligibleBean(String beanName) { return isEligibleAdvisorBean(beanName); } } } @SuppressWarnings("serial") public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator { private static final Comparator<Advisor> DEFAULT_PRECEDENCE_COMPARATOR = new AspectJPrecedenceComparator(); /** * 將通知進行排序,同一個切面的通知具有相同的順序, * 進入連接點時,優先級高的通知先執行,從連接點返回時,優先級低的通知先執行。 */ @Override @SuppressWarnings("unchecked") protected List<Advisor> sortAdvisors(List<Advisor> advisors) { final List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors = new ArrayList<>(advisors.size()); for (final Advisor element : advisors) { partiallyComparableAdvisors.add( new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR)); } final List<PartiallyComparableAdvisorHolder> sorted = PartialOrder.sort(partiallyComparableAdvisors); if (sorted != null) { final List<Advisor> result = new ArrayList<>(advisors.size()); for (final PartiallyComparableAdvisorHolder pcAdvisor : sorted) { result.add(pcAdvisor.getAdvisor()); } return result; } else { return super.sortAdvisors(advisors); } } @Override protected void extendAdvisors(List<Advisor> candidateAdvisors) { AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors); } @Override protected boolean shouldSkip(Class<?> beanClass, String beanName) { final List<Advisor> candidateAdvisors = findCandidateAdvisors(); for (final Advisor advisor : candidateAdvisors) { if (advisor instanceof AspectJPointcutAdvisor && ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) { return true; } } return super.shouldSkip(beanClass, beanName); } private static class PartiallyComparableAdvisorHolder implements PartialComparable { private final Advisor advisor; private final Comparator<Advisor> comparator; public PartiallyComparableAdvisorHolder(Advisor advisor, Comparator<Advisor> comparator) { this.advisor = advisor; this.comparator = comparator; } @Override public int compareTo(Object obj) { final Advisor otherAdvisor = ((PartiallyComparableAdvisorHolder) obj).advisor; return comparator.compare(advisor, otherAdvisor); } @Override public int fallbackCompareTo(Object obj) { return 0; } public Advisor getAdvisor() { return advisor; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); final Advice advice = advisor.getAdvice(); sb.append(ClassUtils.getShortName(advice.getClass())); sb.append(": "); if (advisor instanceof Ordered) { sb.append("order ").append(((Ordered) advisor).getOrder()).append(", "); } if (advice instanceof AbstractAspectJAdvice) { final AbstractAspectJAdvice ajAdvice = (AbstractAspectJAdvice) advice; sb.append(ajAdvice.getAspectName()); sb.append(", declaration order "); sb.append(ajAdvice.getDeclarationOrder()); } return sb.toString(); } } } /** * 用於處理容器中所有 AspectJ 註解的切面,並為目標對象創建代理類。 */ @SuppressWarnings("serial") public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator { @Nullable private List<Pattern> includePatterns; // ReflectiveAspectJAdvisorFactory @Nullable private AspectJAdvisorFactory aspectJAdvisorFactory; // BeanFactoryAspectJAdvisorsBuilder @Nullable private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder; /** * 用於匹配 @AspectJ 註解 bean 名稱的正則表達式列表,默認匹配所有。 */ public void setIncludePatterns(List<String> patterns) { includePatterns = new ArrayList<>(patterns.size()); for (final String patternText : patterns) { includePatterns.add(Pattern.compile(patternText)); } } public void setAspectJAdvisorFactory(AspectJAdvisorFactory aspectJAdvisorFactory) { Assert.notNull(aspectJAdvisorFactory, "AspectJAdvisorFactory must not be null"); this.aspectJAdvisorFactory = aspectJAdvisorFactory; } @Override protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) { super.initBeanFactory(beanFactory); if (aspectJAdvisorFactory == null) { aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory); } aspectJAdvisorsBuilder = new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, aspectJAdvisorFactory); } /** * 查找候選的 Advisors */ @Override protected List<Advisor> findCandidateAdvisors() { /** * 根據父類規則查找所有的 Spring Advisors,實現 Advisor 接口的 bean */ final List<Advisor> advisors = super.findCandidateAdvisors(); // 構建所有 Aspect 切面的通知者 if (aspectJAdvisorsBuilder != null) { advisors.addAll(aspectJAdvisorsBuilder.buildAspectJAdvisors()); } return advisors; } @Override protected boolean isInfrastructureClass(Class<?> beanClass) { // 不代理切面類 return super.isInfrastructureClass(beanClass) || aspectJAdvisorFactory != null && aspectJAdvisorFactory.isAspect(beanClass); } /** * 切面 bean 是否能夠應用自動代理 */ protected boolean isEligibleAspectBean(String beanName) { if (includePatterns == null) { return true; } else { for (final Pattern pattern : includePatterns) { if (pattern.matcher(beanName).matches()) { return true; } } return false; } } /** * Subclass of BeanFactoryAspectJAdvisorsBuilderAdapter that delegates to * surrounding AnnotationAwareAspectJAutoProxyCreator facilities. */ private class BeanFactoryAspectJAdvisorsBuilderAdapter extends BeanFactoryAspectJAdvisorsBuilder { public BeanFactoryAspectJAdvisorsBuilderAdapter( ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) { super(beanFactory, advisorFactory); } @Override protected boolean isEligibleBean(String beanName) { return isEligibleAspectBean(beanName); } } }
通過 ProxyFactory 創建代理類
/** * 代理配置:保證所有的代理創建者都有一致的屬性配置 */ public class ProxyConfig implements Serializable { /** use serialVersionUID from Spring 1.2 for interoperability. */ private static final long serialVersionUID = -8409359707199703185L; /** * 是否是基於類的代理,默認是基於接口的代理 */ private boolean proxyTargetClass = false; /** * 是否執行代理優化,【如果為 true,在代理創建完畢後,修改通知將沒有效果】 */ private boolean optimize = false; /** * 是否不允許將代理類強轉為 Advised,默認可以 */ boolean opaque = false; /** * 代理類是否需要暴露到 AopContext 的 currentProxy 中 */ boolean exposeProxy = false; /** * 是否凍結代理配置,凍結後不可修改 */ private boolean frozen = false; public void setProxyTargetClass(boolean proxyTargetClass) { this.proxyTargetClass = proxyTargetClass; } public boolean isProxyTargetClass() { return proxyTargetClass; } public void setOptimize(boolean optimize) { this.optimize = optimize; } public boolean isOptimize() { return optimize; } public void setOpaque(boolean opaque) { this.opaque = opaque; } public boolean isOpaque() { return opaque; } public void setExposeProxy(boolean exposeProxy) { this.exposeProxy = exposeProxy; } public boolean isExposeProxy() { return exposeProxy; } public void setFrozen(boolean frozen) { this.frozen = frozen; } public boolean isFrozen() { return frozen; } /** * 從另一個 ProxyConfig 中復制屬性 */ public void copyFrom(ProxyConfig other) { Assert.notNull(other, "Other ProxyConfig object must not be null"); proxyTargetClass = other.proxyTargetClass; optimize = other.optimize; exposeProxy = other.exposeProxy; frozen = other.frozen; opaque = other.opaque; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("proxyTargetClass=").append(proxyTargetClass).append("; "); sb.append("optimize=").append(optimize).append("; "); sb.append("opaque=").append(opaque).append("; "); sb.append("exposeProxy=").append(exposeProxy).append("; "); sb.append("frozen=").append(frozen); return sb.toString(); } } /** * AOP 配置管理器的基類 */ public class AdvisedSupport extends ProxyConfig implements Advised { /** use serialVersionUID from Spring 2.0 for interoperability. */ private static final long serialVersionUID = 2651364800145442165L; public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE; /** AOP 通知的目標對象 */ TargetSource targetSource = EMPTY_TARGET_SOURCE; /** 是否已經為特定目標類型篩選過 Advisor */ private boolean preFiltered = false; /** * 通知者鏈工廠 */ AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory(); /** 目標方法和通知者鏈緩存 */ private transient Map<MethodCacheKey, List<Object>> methodCache; /** * 代理類實現的接口列表 */ private List<Class<?>> interfaces = new ArrayList<>(); /** * 通知者列表 */ private List<Advisor> advisors = new ArrayList<>(); /** * 通知者數組 */ private Advisor[] advisorArray = new Advisor[0]; public AdvisedSupport() { this.methodCache = new ConcurrentHashMap<>(32); } public AdvisedSupport(Class<?>... interfaces) { this(); setInterfaces(interfaces); } public void setTarget(Object target) { setTargetSource(new SingletonTargetSource(target)); } @Override public void setTargetSource(@Nullable TargetSource targetSource) { this.targetSource = (targetSource != null ? targetSource : EMPTY_TARGET_SOURCE); } @Override public TargetSource getTargetSource() { return this.targetSource; } public void setTargetClass(@Nullable Class<?> targetClass) { this.targetSource = EmptyTargetSource.forClass(targetClass); } @Override @Nullable public Class<?> getTargetClass() { return this.targetSource.getTargetClass(); } @Override public void setPreFiltered(boolean preFiltered) { this.preFiltered = preFiltered; } @Override public boolean isPreFiltered() { return this.preFiltered; } public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) { Assert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null"); this.advisorChainFactory = advisorChainFactory; } public AdvisorChainFactory getAdvisorChainFactory() { return this.advisorChainFactory; } public void setInterfaces(Class<?>... interfaces) { Assert.notNull(interfaces, "Interfaces must not be null"); this.interfaces.clear(); for (Class<?> ifc : interfaces) { addInterface(ifc); } } /** * 增加一個新的代理接口 */ public void addInterface(Class<?> intf) { Assert.notNull(intf, "Interface must not be null"); if (!intf.isInterface()) { throw new IllegalArgumentException("[" + intf.getName() + "] is not an interface"); } if (!this.interfaces.contains(intf)) { this.interfaces.add(intf); adviceChanged(); } } /** * 移除一個代理接口 */ public boolean removeInterface(Class<?> intf) { return this.interfaces.remove(intf); } @Override public Class<?>[] getProxiedInterfaces() { return ClassUtils.toClassArray(this.interfaces); } @Override public boolean isInterfaceProxied(Class<?> intf) { for (Class<?> proxyIntf : this.interfaces) { if (intf.isAssignableFrom(proxyIntf)) { return true; } } return false; } @Override public final Advisor[] getAdvisors() { return this.advisorArray; } @Override public void addAdvisor(Advisor advisor) { int pos = this.advisors.size(); addAdvisor(pos, advisor); } @Override public void addAdvisor(int pos, Advisor advisor) throws AopConfigException { if (advisor instanceof IntroductionAdvisor) { validateIntroductionAdvisor((IntroductionAdvisor) advisor); } addAdvisorInternal(pos, advisor); } @Override public boolean removeAdvisor(Advisor advisor) { int index = indexOf(advisor); if (index == -1) { return false; } else { removeAdvisor(index); return true; } } @Override public void removeAdvisor(int index) throws AopConfigException { if (isFrozen()) { throw new AopConfigException("Cannot remove Advisor: Configuration is frozen."); } if (index < 0 || index > this.advisors.size() - 1) { throw new AopConfigException("Advisor index " + index + " is out of bounds: " + "This configuration only has " + this.advisors.size() + " advisors."); } Advisor advisor = this.advisors.get(index); if (advisor instanceof IntroductionAdvisor) { IntroductionAdvisor ia = (IntroductionAdvisor) advisor; // We need to remove introduction interfaces. for (int j = 0; j < ia.getInterfaces().length; j++) { removeInterface(ia.getInterfaces()[j]); } } this.advisors.remove(index); updateAdvisorArray(); adviceChanged(); } @Override public int indexOf(Advisor advisor) { Assert.notNull(advisor, "Advisor must not be null"); return this.advisors.indexOf(advisor); } @Override public boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException { Assert.notNull(a, "Advisor a must not be null"); Assert.notNull(b, "Advisor b must not be null"); int index = indexOf(a); if (index == -1) { return false; } removeAdvisor(index); addAdvisor(index, b); return true; } public void addAdvisors(Advisor... advisors) { addAdvisors(Arrays.asList(advisors)); } public void addAdvisors(Collection<Advisor> advisors) { if (isFrozen()) { throw new AopConfigException("Cannot add advisor: Configuration is frozen."); } if (!CollectionUtils.isEmpty(advisors)) { for (Advisor advisor : advisors) { if (advisor instanceof IntroductionAdvisor) { validateIntroductionAdvisor((IntroductionAdvisor) advisor); } Assert.notNull(advisor, "Advisor must not be null"); this.advisors.add(advisor); } updateAdvisorArray(); adviceChanged(); } } private void validateIntroductionAdvisor(IntroductionAdvisor advisor) { advisor.validateInterfaces(); // If the advisor passed validation, we can make the change. Class<?>[] ifcs = advisor.getInterfaces(); for (Class<?> ifc : ifcs) { addInterface(ifc); } } private void addAdvisorInternal(int pos, Advisor advisor) throws AopConfigException { Assert.notNull(advisor, "Advisor must not be null"); if (isFrozen()) { throw new AopConfigException("Cannot add advisor: Configuration is frozen."); } if (pos > this.advisors.size()) { throw new IllegalArgumentException( "Illegal position " + pos + " in advisor list with size " + this.advisors.size()); } this.advisors.add(pos, advisor); updateAdvisorArray(); adviceChanged(); } protected final void updateAdvisorArray() { this.advisorArray = this.advisors.toArray(new Advisor[0]); } protected final List<Advisor> getAdvisorsInternal() { return this.advisors; } @Override public void addAdvice(Advice advice) throws AopConfigException { int pos = this.advisors.size(); addAdvice(pos, advice); } @Override public void addAdvice(int pos, Advice advice) throws AopConfigException { Assert.notNull(advice, "Advice must not be null"); if (advice instanceof IntroductionInfo) { // We don‘t need an IntroductionAdvisor for this kind of introduction: // It‘s fully self-describing. addAdvisor(pos, new DefaultIntroductionAdvisor(advice, (IntroductionInfo) advice)); } else if (advice instanceof DynamicIntroductionAdvice) { // We need an IntroductionAdvisor for this kind of introduction. throw new AopConfigException("DynamicIntroductionAdvice may only be added as part of IntroductionAdvisor"); } else { addAdvisor(pos, new DefaultPointcutAdvisor(advice)); } } @Override public boolean removeAdvice(Advice advice) throws AopConfigException { int index = indexOf(advice); if (index == -1) { return false; } else { removeAdvisor(index); return true; } } @Override public int indexOf(Advice advice) { Assert.notNull(advice, "Advice must not be null"); for (int i = 0; i < this.advisors.size(); i++) { Advisor advisor = this.advisors.get(i); if (advisor.getAdvice() == advice) { return i; } } return -1; } public boolean adviceIncluded(@Nullable Advice advice) { if (advice != null) { for (Advisor advisor : this.advisors) { if (advisor.getAdvice() == advice) { return true; } } } return false; } /** * 計算給定通知類型的通知者個數 */ public int countAdvicesOfType(@Nullable Class<?> adviceClass) { int count = 0; if (adviceClass != null) { for (Advisor advisor : this.advisors) { if (adviceClass.isInstance(advisor.getAdvice())) { count++; } } } return count; } /** * 獲取指定方法的 MethodInterceptor 列表 */ public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) { MethodCacheKey cacheKey = new MethodCacheKey(method); List<Object> cached = this.methodCache.get(cacheKey); if (cached == null) { cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice( this, method, targetClass); this.methodCache.put(cacheKey, cached); } return cached; } protected void adviceChanged() { this.methodCache.clear(); } protected void copyConfigurationFrom(AdvisedSupport other) { copyConfigurationFrom(other, other.targetSource, new ArrayList<>(other.advisors)); } /** * Copy the AOP configuration from the given AdvisedSupport object, * but allow substitution of a fresh TargetSource and a given interceptor chain. */ protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List<Advisor> advisors) { copyFrom(other); this.targetSource = targetSource; this.advisorChainFactory = other.advisorChainFactory; this.interfaces = new ArrayList<>(other.interfaces); for (Advisor advisor : advisors) { if (advisor instanceof IntroductionAdvisor) { validateIntroductionAdvisor((IntroductionAdvisor) advisor); } Assert.notNull(advisor, "Advisor must not be null"); this.advisors.add(advisor); } updateAdvisorArray(); adviceChanged(); } AdvisedSupport getConfigurationOnlyCopy() { AdvisedSupport copy = new AdvisedSupport(); copy.copyFrom(this); copy.targetSource = EmptyTargetSource.forClass(getTargetClass(), getTargetSource().isStatic()); copy.advisorChainFactory = this.advisorChainFactory; copy.interfaces = this.interfaces; copy.advisors = this.advisors; copy.updateAdvisorArray(); return copy; } @Override public String toProxyConfigString() { return toString(); } /** * For debugging/diagnostic use. */ @Override public String toString() { StringBuilder sb = new StringBuilder(getClass().getName()); sb.append(": ").append(this.interfaces.size()).append(" interfaces "); sb.append(ClassUtils.classNamesToString(this.interfaces)).append("; "); sb.append(this.advisors.size()).append(" advisors "); sb.append(this.advisors).append("; "); sb.append("targetSource [").append(this.targetSource).append("]; "); sb.append(super.toString()); return sb.toString(); } private static final class MethodCacheKey implements Comparable<MethodCacheKey> { private final Method method; private final int hashCode; public MethodCacheKey(Method method) { this.method = method; this.hashCode = method.hashCode(); } @Override public boolean equals(Object other) { return (this == other || (other instanceof MethodCacheKey && this.method == ((MethodCacheKey) other).method)); } @Override public int hashCode() { return this.hashCode; } @Override public String toString() { return this.method.toString(); } @Override public int compareTo(MethodCacheKey other) { int result = this.method.getName().compareTo(other.method.getName()); if (result == 0) { result = this.method.toString().compareTo(other.method.toString()); } return result; } } }
代理創建
通過 AopProxyFactory#createAopProxy 創建 AopProxy,再通過 AopProxy#getProxy 創建代理類。
/** * 基於 AdvisedSupport 創建 AopProxy 的工廠 */ public interface AopProxyFactory { /** * 基於指定的 AOP 配置創建 AopProxy */ AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException; } @SuppressWarnings("serial") public class DefaultAopProxyFactory implements AopProxyFactory, Serializable { @Override public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException { if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) { final 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."); } // 目標類型是接口 || 代理類 if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) { return new JdkDynamicAopProxy(config); } return new ObjenesisCglibAopProxy(config); } else { return new JdkDynamicAopProxy(config); } } /** * 沒有用戶定義的代理接口 */ private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) { final Class<?>[] ifcs = config.getProxiedInterfaces(); return ifcs.length == 0 || ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0]); } } /** * 已配置AOP代理的委托接口,用於創建實際的代理對象 */ public interface AopProxy { /** * 創建一個新的代理對象 */ Object getProxy(); /** * 基於指定的類加載器創建一個新的代理對象 */ Object getProxy(@Nullable ClassLoader classLoader); } /** * 基於 JDK 動態代理實現的 AopProxy */ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable { private static final long serialVersionUID = 5531744639992436476L; private static final Log logger = LogFactory.getLog(JdkDynamicAopProxy.class); /** 代理配置 */ private final AdvisedSupport advised; /** * equals 方法定義在代理接口中? */ private boolean equalsDefined; /** * hashCode 定義在代理接口中? */ private boolean hashCodeDefined; 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"); } advised = config; } @Override public Object getProxy() { return getProxy(ClassUtils.getDefaultClassLoader()); } @Override public Object getProxy(@Nullable ClassLoader classLoader) { if (logger.isTraceEnabled()) { logger.trace("Creating JDK dynamic proxy: " + advised.getTargetSource()); } // 讀取所有代理接口 final Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(advised, true); // 查找 equals 和 hashCode 方法 findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); // 創建代理類 return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); } /** * 查找 equals 和 hashCode 方法 */ private void findDefinedEqualsAndHashCodeMethods(Class<?>[] proxiedInterfaces) { for (final Class<?> proxiedInterface : proxiedInterfaces) { final Method[] methods = proxiedInterface.getDeclaredMethods(); for (final Method method : methods) { // 如果是 equals 方法 if (AopUtils.isEqualsMethod(method)) { equalsDefined = true; } // 如果是 hashCode 方法 if (AopUtils.isHashCodeMethod(method)) { hashCodeDefined = true; } if (equalsDefined && hashCodeDefined) { return; } } } } /** * 執行核心調用 */ @Override @Nullable public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { MethodInvocation invocation; Object oldProxy = null; boolean setProxyContext = false; final TargetSource targetSource = advised.targetSource; Object target = null; try { // 1)目標方法是 equals if (!equalsDefined && AopUtils.isEqualsMethod(method)) { // The target does not implement the equals(Object) method itself. return equals(args[0]); } // 2)目標方法是 hashCode else if (!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(advised); } else if (!advised.opaque && method.getDeclaringClass().isInterface() && method.getDeclaringClass().isAssignableFrom(Advised.class)) { // Service invocations on ProxyConfig with the proxy config... return AopUtils.invokeJoinpointUsingReflection(advised, method, args); } Object retVal; // 將代理類寫入 AopContext 中 if (advised.exposeProxy) { oldProxy = AopContext.setCurrentProxy(proxy); setProxyContext = true; } // 盡量減少目標對象的持有時間,它可能來自於對象池 target = targetSource.getTarget(); final Class<?> targetClass = target != null ? target.getClass() : null; // 獲取方法的攔截鏈 final List<Object> chain = advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); // 1)沒有攔截鏈,則直接觸發目標方法調用 if (chain.isEmpty()) { // 將可變參數封裝到數組中 final Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); // 反射調用目標方法 retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse); } else { // 創建 ReflectiveMethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); // 執行攔截鏈和目標方法 retVal = invocation.proceed(); } final Class<?> returnType = method.getReturnType(); // 1)某種兼容 if (retVal != null && retVal == target && returnType != Object.class && returnType.isInstance(proxy) && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { retVal = proxy; } // 2)方法的返回類型聲明為原生類型 && 但是返回了 null else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) { throw new AopInvocationException( "Null return value from advice does not match primitive return type for: " + method); } return retVal; } finally { if (target != null && !targetSource.isStatic()) { // Must have come from TargetSource. targetSource.releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } } @Override public boolean equals(@Nullable Object other) { if (other == this) { return true; } if (other == null) { return false; } JdkDynamicAopProxy otherProxy; if (other instanceof JdkDynamicAopProxy) { otherProxy = (JdkDynamicAopProxy) other; } else if (Proxy.isProxyClass(other.getClass())) { final InvocationHandler ih = Proxy.getInvocationHandler(other); if (!(ih instanceof JdkDynamicAopProxy)) { return false; } otherProxy = (JdkDynamicAopProxy) ih; } else { // Not a valid comparison... return false; } // If we get here, otherProxy is the other AopProxy. return AopProxyUtils.equalsInProxy(advised, otherProxy.advised); } @Override public int hashCode() { return JdkDynamicAopProxy.class.hashCode() * 13 + advised.getTargetSource().hashCode(); } }
AOP 代理類的創建