FactoryBean类的核心是通过getObject()方法来创建对象的,所以我们直接研究这个方法(源码分析来自于Spring5.1.5):
ProxyFactoryBean.class
主代码块:
/**
* Return a proxy. Invoked when clients obtain beans from this factory bean.
* Create an instance of the AOP proxy to be returned by this factory.
* The instance will be cached for a singleton, and create on each call to
* {@code getObject()} for a proxy.
* @return a fresh AOP proxy reflecting the current state of this factory
*/
//返回一个代理。当客户端从该工厂bean获取bean时调用。创建由这个工厂返回的AOP代理的一个实例。
@Override
@Nullable
public Object getObject() throws BeansException {
//获取advisor(拦截器)链 见:代码块1
//第一次创建好advisor链(集合)后,以后再次获取的时候就不用创建了,直接取就行了。
//作用:在返回代理对象之前,获取到配置文件配置的所有的advisor,并且放到一个集合中,供后续目标对象的某个方法被调用时,
//去遍历advisro链,然后根据每个advisor的Pointcut去决定执行对应的Advice
initializeAdvisorChain();
//判断是不是单例(一般情况下,bean中没有显示设置这个属性的话,该属性默认为true)(这里的bean是指的:ProxyFactoryBean)
if (isSingleton()) {
//获取单例AOP代理对象 见:代码库2
return getSingletonInstance();
}
else {
if (this.targetName == null) {
logger.info("Using non-singleton proxies with singleton targets is often undesirable. " +
"Enable prototype proxies by setting the 'targetName' property.");
}
//获取原型单例AOP代理对象
//这个和上面的getSingletonInstance()没太大区别,只是这个方法每次调用都会创建一个新的代理对象而已。所以不做进一步研究
return newPrototypeInstance();
}
}
代码块1:initializeAdvisorChain()
//ProxyFactoryBean.class
/**
* Create the advisor (interceptor) chain. Advisors that are sourced
* from a BeanFactory will be refreshed each time a new prototype instance
* is added. Interceptors added programmatically through the factory API
* are unaffected by such changes.
*/
//创建advisor(拦截器)链。Advisors(拦截器)是通过工厂API以编程方式添加的,见 图1中的interceptorNames属性和myAdvisor bean
private synchronized void initializeAdvisorChain() throws AopConfigException, BeansException {
//判断advisorChain是否已经初始化
if (this.advisorChainInitialized) {
return;
}
//对interceptorNames进行一系列判断
//private String[] interceptorNames;
if (!ObjectUtils.isEmpty(this.interceptorNames)) {
if (this.beanFactory == null) {
throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
"- cannot resolve interceptor names " + Arrays.asList(this.interceptorNames));
}
// Globals can't be last unless we specified a targetSource using the property...
if (this.interceptorNames[this.interceptorNames.length - 1].endsWith(GLOBAL_SUFFIX) &&
this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) {
throw new AopConfigException("Target required after globals");
}
// Materialize interceptor chain from bean names.
//循环interceptorNames,就是图1中的interceptorNames属性中的<list>里面的一个一个字符串
for (String name : this.interceptorNames) {
if (logger.isTraceEnabled()) {
logger.trace("Configuring advisor or advice '" + name + "'");
}
if (name.endsWith(GLOBAL_SUFFIX)) {
if (!(this.beanFactory instanceof ListableBeanFactory)) {
throw new AopConfigException(
"Can only use global advisors or interceptors with a ListableBeanFactory");
}
addGlobalAdvisor((ListableBeanFactory) this.beanFactory,
name.substring(0, name.length() - GLOBAL_SUFFIX.length()));
}
else {
// If we get here, we need to add a named interceptor.
// We must check if it's a singleton or prototype.
Object advice;
if (this.singleton || this.beanFactory.isSingleton(name)) {
// Add the real Advisor/Advice to the chain.
//通过bean工厂,获取到name对应的Advice对象,即:图1中的myAdvisor这个bean
advice = this.beanFactory.getBean(name);
}
else {
// It's a prototype Advice or Advisor: replace with a prototype.
// Avoid unnecessary creation of prototype bean just for advisor chain initialization.
advice = new PrototypePlaceholderAdvisor(name);
}
//创建并且添加Advisor链中
//见 :内部代码块1
addAdvisorOnChainCreation(advice, name);
}
}
}
this.advisorChainInitialized = true;
}
内部代码块1:
/**
* Invoked when advice chain is created.
* <p>Add the given advice, advisor or object to the interceptor list.
* Because of these three possibilities, we can't type the signature
* more strongly.
* @param next advice, advisor or target object
* @param name bean name from which we obtained this object in our owning
* bean factory
*/
//创建advice链的时候添加advice、advisor 、object
private void addAdvisorOnChainCreation(Object next, String name) {
// We need to convert to an Advisor if necessary so that our source reference
// matches what we find from superclass interceptors.
//如果不是divisor则转换成一个advisor
Advisor advisor = namedBeanToAdvisor(next);
if (logger.isTraceEnabled()) {
logger.trace("Adding advisor with name '" + name + "'");
}
//添加到advisor链中 见:内部代码块2
addAdvisor(advisor);
}
内部代码块2
@Override
public void addAdvisor(Advisor advisor) {
int pos = this.advisors.size();
//添加到advisor集合中
//private List<Advisor> advisors = new ArrayList<>();
//Advisor 见:内部代码块3
addAdvisor(pos, advisor);
}
内部代码块3
Advisor是一个根接口,用户Advice和Pointcut的组合。方法很少,就只有一个getAdvice()方法,用于获取Advice。见 图2
Advice:执行的动作,即方法 Pointcut:执行动作的地方(切入点)
图1:
代码块2:getSingletonInstance()
/**
* Return the singleton instance of this class's proxy object,
* lazily creating it if it hasn't been created already.
* @return the shared singleton proxy
*/
//返回单例的代理对象(所以说代理对象是不是单例,由ProxyFactoryBean是不是单例决定)
private synchronized Object getSingletonInstance() {
//如果单例的代理对象已经存在(第一次创建时被缓存起来了),则直接返回
if (this.singletonInstance == null) {
this.targetSource = freshTargetSource();
if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
// Rely on AOP infrastructure to tell us what interfaces to proxy.
//获取要代理的目标对象的Class对象
Class<?> targetClass = getTargetClass();
if (targetClass == null) {
throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
}
//设置要代理对象所实现的接口(就是目标对象的接口,因为jdk动态代理需要使用到)
//见 内部代码块1
setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
}
// Initialize the shared singleton instance.
super.setFrozen(this.freezeProxy);
//正真创建aop代理对象
//createAopProxy(): 见 内部代码块3
//getProxy(): 见 第16章->代码块2
this.singletonInstance = getProxy(createAopProxy());
}
return this.singletonInstance;
}
内部代码块1
AdvisedSupport.class
/**
* Set the interfaces to be proxied.
*/
public void setInterfaces(Class<?>... interfaces) {
Assert.notNull(interfaces, "Interfaces must not be null");
this.interfaces.clear();
for (Class<?> ifc : interfaces) {
//见 内部代码块2
addInterface(ifc);
}
}
内部代码块2
/**
* Add a new proxied interface.
* @param intf the additional interface to proxy
*/
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)) {
//Interfaces to be implemented by the proxy. Held in List to keep the order of registration, to create JDK proxy with specified order of interfaces.
//就是一个集合
//private List<Class<?>> interfaces = new ArrayList<>();
this.interfaces.add(intf);
adviceChanged();
}
}
内部代码块3:createAopProxy()
/**
* Subclasses should call this to get a new AOP proxy. They should <b>not</b>
* create an AOP proxy with {@code this} as an argument.
*/
//返回AopProxy,它是一个接口,这个对象是创建Aop代理对象的对象。有两个实现类:CglibAopProxy(cglib创建代理对象) 和 JdkDynamicAopProxy(jdk创建代理对象)
//见图1:
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
//通过AopProxy工厂创建AopProxy
//getAopProxyFactory() 见 内部代码块4
//createAopProxy() 见 第16讲->代码块1 //总结一句话:根据不同的配置信息,决定返回不同类型的代理(AopProxy)
return getAopProxyFactory().createAopProxy(this);
}
内部代码块4
//ProxyCreatorSupport.class
/**
* Return the AopProxyFactory that this ProxyConfig uses.
*/
//这个方法存在于父类ProxyCreatorSupport中
public AopProxyFactory getAopProxyFactory() {
//这个对象在父类的构造方法中创建的
//见 内部代码块5
return this.aopProxyFactory;
}
内部代码块5
ProxyCreatorSupport.class
/**
* Base class for proxy factories.
* Provides convenient access to a configurable AopProxyFactory.
*/
@SuppressWarnings("serial")
public class ProxyCreatorSupport extends AdvisedSupport {
private AopProxyFactory aopProxyFactory;
......
/**
* Create a new ProxyCreatorSupport instance.
*/
public ProxyCreatorSupport() {
//默认的AopProxyFactory
//见 内部代码块6
this.aopProxyFactory = new DefaultAopProxyFactory();
}
......
}
内部代码块6
/**
* Default {@link AopProxyFactory} implementation, creating either a CGLIB proxy
* or a JDK dynamic proxy.
*
* <p>Creates a CGLIB proxy if one the following is true for a given
* {@link AdvisedSupport} instance:
* <ul>
* <li>the {@code optimize} flag is set
* <li>the {@code proxyTargetClass} flag is set
* <li>no proxy interfaces have been specified
* </ul>
*
* <p>In general, specify {@code proxyTargetClass} to enforce a CGLIB proxy,
* or specify one or more interfaces to use a JDK dynamic proxy.
*/
@SuppressWarnings("serial")
//该类详解 见 第16讲->代码块1
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
//就是通过调用这个方法创建AopProxy 的
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
//通过jdk的方式创建代理对象
return new JdkDynamicAopProxy(config);
}
//通过cglib的方式创建代理对象
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
/**
* Determine whether the supplied {@link AdvisedSupport} has only the
* {@link org.springframework.aop.SpringProxy} interface specified
* (or no proxy interfaces specified at all).
*/
private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
Class<?>[] ifcs = config.getProxiedInterfaces();
return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
}
}