ProxyFactory就springAOP创建代理的工厂,现在以此为入口进行aop源码的解读。
首先看ProxyFactory的结构图:
TargetClassAware
根据结构图,先看接口TargetClassAware,该接口是暴露代理的目标类的最小实现,该接口只有一个方法,
Class<?> getTargetClass();
获取实现对象的目标类,当目标类未知,返回null。
接口Advised
接下来看它的子接口Advised,
接口说明: 由类持有一个AOP代理工厂配置的实现,配置包拦截器、其他的通知、顾问、代理的接口。
spring的任何AOP代理都能强转为此接口,这样就能够允许操作aop的通知。
接口方法如下:
//通知配置是否冻结,冻结后通知不能做改变
boolean isFrozen();
//是否代理目标类
boolean isProxyTargetClass();
//返回aop的代理接口,不包括目标类
Class<?>[] getProxiedInterfaces();
boolean isInterfaceProxied(Class<?> intf);
void setTargetSource(TargetSource targetSource);
TargetSource getTargetSource();
//通过aop框架,作为用AopContext可检索的ThreadLocal向外暴露
//当一个advised object需要调用另外一个advised object时有用。
void setExposeProxy(boolean exposeProxy);
boolean isExposeProxy();
//设置代理配置为提前过滤,因此它包括适当的advisors(通过匹配代理目标类)
void setPreFiltered(boolean preFiltered);
boolean isPreFiltered();
Advisor[] getAdvisors();
void addAdvisor(Advisor advisor) throws AopConfigException;
void addAdvisor(int pos, Advisor advisor) throws AopConfigException;
boolean removeAdvisor(Advisor advisor);
void removeAdvisor(int index) throws AopConfigException;
int indexOf(Advisor advisor);
boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;
void addAdvice(Advice advice) throws AopConfigException;
void addAdvice(int pos, Advice advice) throws AopConfigException;
boolean removeAdvice(Advice advice);
int indexOf(Advice advice);
String toProxyConfigString();
ProxyConfig类:
方便的超类对于创建代理的配置,确保所以的代理创建对象有一致的属性。
方法如下:
public void setProxyTargetClass(boolean proxyTargetClass) {
this.proxyTargetClass = proxyTargetClass;
}
public boolean isProxyTargetClass() {
return this.proxyTargetClass;
}
public void setOptimize(boolean optimize) {
this.optimize = optimize;
}
public boolean isOptimize() {
return this.optimize;
}
public void setOpaque(boolean opaque) {
this.opaque = opaque;
}
public boolean isOpaque() {
return this.opaque;
}
public void setExposeProxy(boolean exposeProxy) {
this.exposeProxy = exposeProxy;
}
public boolean isExposeProxy() {
return this.exposeProxy;
}
public void setFrozen(boolean frozen) {
this.frozen = frozen;
}
public boolean isFrozen() {
return this.frozen;
}
public void copyFrom(ProxyConfig other) {
Assert.notNull(other, "Other ProxyConfig object must not be null");
this.proxyTargetClass = other.proxyTargetClass;
this.optimize = other.optimize;
this.exposeProxy = other.exposeProxy;
this.frozen = other.frozen;
this.opaque = other.opaque;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("proxyTargetClass=").append(this.proxyTargetClass).append("; ");
sb.append("optimize=").append(this.optimize).append("; ");
sb.append("opaque=").append(this.opaque).append("; ");
sb.append("exposeProxy=").append(this.exposeProxy).append("; ");
sb.append("frozen=").append(this.frozen);
return sb.toString();
}
发现其中有一些方法是为了实现Advised接口而准备的。
AdvisedSupport类:
aop代理配置管理的基类。
自身不是aop代理,但其子类是能够直接获取aop代理实例的常规工厂。
该类为子类管理创建Advices和Advisors利用便利,但它实际上没有实现代理的创建方法,由子类各自提供。
构造函数代码实现:
private transient Map<MethodCacheKey, List<Object>> methodCache;
//
public AdvisedSupport() {
initMethodCache();
}
public AdvisedSupport(Class<?>[] interfaces) {
this();
setInterfaces(interfaces);
}
//默认初始化是创建32个map
private void initMethodCache() {
this.methodCache = new ConcurrentHashMap<MethodCacheKey, List<Object>>(32);
}
对于带接口数组参数的构造函数,设置先清空,后重新设置:
private List<Class<?>> interfaces = new ArrayList<Class<?>>();
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);
//当代理接口有更改,也同时清空methodCache
adviceChanged();
}
}
protected void adviceChanged() {
this.methodCache.clear();
}
public boolean removeInterface(Class<?> intf) {
return this.interfaces.remove(intf);
}
@Override
public Class<?>[] getProxiedInterfaces() {
return this.interfaces.toArray(new Class<?>[this.interfaces.size()]);
}
//判断所有的目标类是否是接口
@Override
public boolean isInterfaceProxied(Class<?> intf) {
for (Class<?> proxyIntf : this.interfaces) {
if (intf.isAssignableFrom(proxyIntf)) {
return true;
}
}
return false;
}
设置代理目标的方法:
public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE;
TargetSource targetSource = EMPTY_TARGET_SOURCE;
//将根据给得的object创建 SingletonTargetSource
public void setTarget(Object target) {
setTargetSource(new SingletonTargetSource(target));
}
//直接设置TargetSource相应的接口实现,若为空,返回EMPTY_TARGET_SOURCE
@Override
public void setTargetSource(TargetSource targetSource) {
this.targetSource = (targetSource != null ? targetSource : EMPTY_TARGET_SOURCE);
}
//该代理目标类能够转为targetClass,该方法是前面两个方法的替代:当我们想要一个没有可达TargetSource的代理类
public void setTargetClass(Class<?> targetClass) {
this.targetSource = EmptyTargetSource.forClass(targetClass);
}
@Override
public Class<?> getTargetClass() {
return this.targetSource.getTargetClass();
}
设置是否预先过滤,默认为false:
private boolean preFiltered = false;
@Override
public void setPreFiltered(boolean preFiltered) {
this.preFiltered = preFiltered;
}
@Override
public boolean isPreFiltered() {
return this.preFiltered;
}
设置AdvisorChainFactory:
AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();
public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) {
Assert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null");
this.advisorChainFactory = advisorChainFactory;
}
public AdvisorChainFactory getAdvisorChainFactory() {
return this.advisorChainFactory;
}
对于Advisor的操作:
private Advisor[] advisorArray = new Advisor[0];
//获取操作
protected final List<Advisor> getAdvisorsInternal() {
return this.advisors;
}
@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);
}
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[this.advisors.size()]);
}
//对于多个Advisor的添加
public void addAdvisors(Advisor... advisors) {
addAdvisors(Arrays.asList(advisors));
}
//对于Advisor集合的添加
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();
}
}
//删除操作
@Override
public boolean removeAdvisor(Advisor advisor) {
int index = indexOf(advisor);
if (index == -1) {
return false;
}
else {
removeAdvisor(index);
return true;
}
}
@Override
public int indexOf(Advisor advisor) {
Assert.notNull(advisor, "Advisor must not be null");
return this.advisors.indexOf(advisor);
}
@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 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;
}
对于Advice的操作:
@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(Advice advice) {
if (advice != null) {
for (Advisor advisor : this.advisors) {
if (advisor.getAdvice() == advice) {
return true;
}
}
}
return false;
}
public int countAdvicesOfType(Class<?> adviceClass) {
int count = 0;
if (adviceClass != null) {
for (Advisor advisor : this.advisors) {
if (adviceClass.isInstance(advisor.getAdvice())) {
count++;
}
}
}
return count;
}
通过上面对Advice相关代码的解读 ,可以看出,Advice是Advisor的成员。
通过字面意思,Advisor是顾问,Advice是顾问中的通知,当操作了通知,也就是操作了顾问.
该类也提供了一些配置的拷贝操作方法:
protected void copyConfigurationFrom(AdvisedSupport other) {
copyConfigurationFrom(other, other.targetSource, new ArrayList<Advisor>(other.advisors));
}
protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List<Advisor> advisors) {
copyFrom(other);
this.targetSource = targetSource;
this.advisorChainFactory = other.advisorChainFactory;
this.interfaces = new ArrayList<Class<?>>(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;
}
ProxyCreatorSupport
接下来看AdvisedSupport的子类ProxyCreatorSupport:代理工厂的基类,提供方便的访问一个可配置的AopProxyFactory。
构造函数:
private AopProxyFactory aopProxyFactory;
public ProxyCreatorSupport() {
this.aopProxyFactory = new DefaultAopProxyFactory();
}
public ProxyCreatorSupport(AopProxyFactory aopProxyFactory) {
Assert.notNull(aopProxyFactory, "AopProxyFactory must not be null");
this.aopProxyFactory = aopProxyFactory;
}
AopProxyFactory也可以自定义设置:
public void setAopProxyFactory(AopProxyFactory aopProxyFactory) {
Assert.notNull(aopProxyFactory, "AopProxyFactory must not be null");
this.aopProxyFactory = aopProxyFactory;
}
public AopProxyFactory getAopProxyFactory() {
return this.aopProxyFactory;
}
该类可以对通知添加监听器:
private List<AdvisedSupportListener> listeners = new LinkedList<AdvisedSupportListener>();
public void addListener(AdvisedSupportListener listener) {
Assert.notNull(listener, "AdvisedSupportListener must not be null");
this.listeners.add(listener);
}
public void removeListener(AdvisedSupportListener listener) {
Assert.notNull(listener, "AdvisedSupportListener must not be null");
this.listeners.remove(listener);
}
//通知的改变,对应的监听器也要相应更新
@Override
protected void adviceChanged() {
super.adviceChanged();
synchronized (this) {
if (this.active) {
for (AdvisedSupportListener listener : this.listeners) {
listener.adviceChanged(this);
}
}
}
}
也提供了一个方法给子类创建一个新的aop代理
/** Set to true when the first AOP proxy has been created */
private boolean active = false;
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
private void activate() {
this.active = true;
for (AdvisedSupportListener listener : this.listeners) {
listener.activated(this);
}
}
protected final synchronized boolean isActive() {
return this.active;
}
ProxyFactory
介绍完了ProxyFactory的父类与父接口,看下来看ProxyFactory类,就更容易理解了。
构造函数:
public ProxyFactory() {
}
public ProxyFactory(Object target) {
setTarget(target);
setInterfaces(ClassUtils.getAllInterfaces(target));
}
public ProxyFactory(Class<?>... proxyInterfaces) {
setInterfaces(proxyInterfaces);
}
public ProxyFactory(Class<?> proxyInterface, Interceptor interceptor) {
addInterface(proxyInterface);
addAdvice(interceptor);
}
public ProxyFactory(Class<?> proxyInterface, TargetSource targetSource) {
addInterface(proxyInterface);
setTargetSource(targetSource);
}
主要是对顾问的通知进行操作。
aop代理的获取:
public Object getProxy() {
return createAopProxy().getProxy();
}
public Object getProxy(ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
public static <T> T getProxy(Class<T> proxyInterface, Interceptor interceptor) {
return (T) new ProxyFactory(proxyInterface, interceptor).getProxy();
}
public static <T> T getProxy(Class<T> proxyInterface, TargetSource targetSource) {
return (T) new ProxyFactory(proxyInterface, targetSource).getProxy();
}
public static Object getProxy(TargetSource targetSource) {
if (targetSource.getTargetClass() == null) {
throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class");
}
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTargetSource(targetSource);
proxyFactory.setProxyTargetClass(true);
return proxyFactory.getProxy();
}