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 代理类的创建的更多相关文章

  1. AOP详解之三-创建AOP代理后记,创建AOP代理

    AOP详解之三-创建AOP代理后记,创建AOP代理. 上篇文章已经获取到了AOP的信息,接下来就是拿着这些AOP的信息去创建代理了. 首先我们看下创建AOP代理的入口处. //这个方法将返回代理类 p ...

  2. Spring AOP 代理类,BeanNameAutoProxyCreator cglib

    BeanNameAutoProxyCreator支持拦截接口和类,但不支持已经被jdk代理过的类$Proxy8.使用cglib才能代理,如下 <!-- 通过bean的名字来匹配选择要代理的bea ...

  3. Spring《八》AOP/代理类定义

    Spring通知 Interception Around通知 MethodInterceptor类(方法执行前后通知) Before通知 MethodBeforeAdvice类(方法执行前通知) Af ...

  4. Spring AOP源码分析(三)创建AOP代理

    摘要: 本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. 目录 一.获取增强器 1. 普通增强器的获取 2. 增加同步实例化增强 ...

  5. Spring AOP学习笔记04:AOP核心实现之创建代理

    上文中,我们分析了对所有增强器的获取以及获取匹配的增强器,在本文中我们就来分析一下Spring AOP中另一部分核心逻辑--代理的创建.这部分逻辑的入口是在wrapIfNecessary()方法中紧接 ...

  6. sping aop 源码分析(-)-- 代理对象的创建过程分析

    测试项目已上传到码云,可以下载:https://gitee.com/yangxioahui/aopdemo.git 具体如下: public interface Calc { Integer add( ...

  7. AOP代理对象生成

    AOP(Aspect-OrientedProgramming,面向方面编程)是OOP(Object-Oriented Programing,面向对象编程)的良好补充与完善,后者侧重于解决 从上到下的存 ...

  8. 用cglib包来为类产生动态代理类对象

    一:在JDK里也有动态代理的类和接口,是Proxy和InvocationHandler,但是Proxy只能为接口产生代理类,借助InvocationHandler的实现类来完成对类对象的代理: 但是在 ...

  9. spring5 源码深度解析----- AOP代理的生成

    在获取了所有对应bean的增强后,便可以进行代理的创建了.回到AbstractAutoProxyCreator的wrapIfNecessary方法中,如下所示: protected static fi ...

随机推荐

  1. leetcode297. 二叉树的序列化与反序列化

    代码 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * ...

  2. 本地安装Mysql后,navicat链接异常:Clinet dose not support authentication protocol request by server ; consider upgrading MySQL client

    第一步:首先通过cmd进入mysql 在命令窗口 输入:mysql -u root -p: 第二步:更改加密方式 mysql> ALTER USER 'root'@'localhost' IDE ...

  3. Linux 的帐号与群组:有效与初始群组、groups, newgrp

    关于群组: 有效与初始群组.groups, newgrp 认识了帐号相关的两个档案 /etc/passwd 与 /etc/shadow 之后,您或许还是会觉得奇怪, 那么群组的设定档在哪里?还有,在 ...

  4. copy模块与fetch模块

    copy:将本地机器上的文件拷贝到远程机器 fetch:将远程机器上的文件拷贝到本地机器 [root@localhost zabbix]# ansible-doc -s copy - name: Co ...

  5. <现代C++实战30讲>笔记 01 | 堆、栈、RAII:C++里该如何管理资源?

    1.堆(heap),动态分配的内存区域,分配之后需手工释放(new, delete, malloc, free) 这种方式需要分配内存,释放内存,因此可能会造成内存泄露,或者内存碎片的问题. 2.栈( ...

  6. Summer training round2 #9(Training28)

    A:签到题 C:模拟搜索题 #include <bits/stdc++.h> #include <cstring> #include <iostream> #inc ...

  7. JavaScript原型初学者指南

    视频Videohttps://www.youtube.com/watch... 前言 如果不好好的学习对象,你就无法在JavaScript中获得很大的成就.它们几乎是JavaScript编程语言的每个 ...

  8. k8sConfigMap资源

    ConfigMap对象用于为容器中的应用提供配置数据以定制程序的行为,不过敏感的配置信息,例如密钥.证书等通常由Secret对象来进行配置.他们将相应的配置信息保存于对象中,而后在pod资源上以存储卷 ...

  9. Java技术综述

    自己打算好好学习下Java,所以想先明晰Java开发中到底有哪些技术,以便以后学习的过程中,可以循序渐进,随着学习的深入,本文将不断更新. Java基础教程将Java的入门基础知识贯穿在一个实例中,逐 ...

  10. [转]C++引用

    引用的概念 引用:就是某一变量(目标)的一个别名,对引用的操作与对变量直接操作完全一样. 引用的声明方法:类型标识符 &引用名=目标变量名: 如下:定义引用ra,它是变量a的引用,即别名. i ...