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();
}
}