Inside-springframework-AOP-creator
来源:互联网 发布:5g网络是什么意思 编辑:程序博客网 时间:2024/05/30 02:25
Inside-springframework-AOP-creator
说明:1)spring在启动时调用AbstractApplicationContext的refresh()方法中的
registerBeanPostProcessors()在beanFactory中注册类型为
BeanPostProcessor的bean(既代理工厂bean)
2)在注册类型为BeanPostProcessor的bean时通过配置文件登记相关Advisor和
Interceptorbean
3)在实例化beanFactory所有singleton bean时,遍历所有已经注册的类型为
BeanPostProcessor的bean,实例化它所代理的bean。如果被代理的bean实现接
口,最后实例化的是代理的JdkDynamicAopProxy类型的bean。
4)spring在执行时会使用java.lang.reflect.Proxy来进行动态代理,如果不实现
接口,则spring会使用CGLIB产生一个子类作为代理类。
☆ 就从这开个头
★ public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext, DisposableBean {
public void refresh() throws BeansException, IllegalStateException {
… …
beanFactory.preInstantiateSingletons(); (1)
… …
}
}
★ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry {
public void preInstantiateSingletons() throws BeansException { (1注)
for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) {
String beanName = (String) it.next();
if (!containsSingleton(beanName) && containsBeanDefinition(beanName)) {
RootBeanDefinition bd = getMergedBeanDefinition(beanName, false);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
Class beanClass = resolveBeanClass(bd, beanName);
if (beanClass != null &&
FactoryBean.class.isAssignableFrom(beanClass)) {
getBean(FACTORY_BEAN_PREFIX + beanName);
}
else {
//样例中需要实例化的beanName为userManager
//是userManagerImpl的接口
getBean(beanName); (2)
}
}
}
}
}
}
★ public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {
public Object getBean(String name, Class requiredType, final Object[] args) throws
BeansException { (2注)
… …
sharedInstance = getSingleton(beanName, new ObjectFactory() {
public Object getObject() throws BeansException {
try {
return createBean(beanName, mergedBeanDefinition, args);(3)
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
… …
}
}
☆ 创建AOP的java动态代理对象
★ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
protected Object createBean(String beanName, RootBeanDefinition
mergedBeanDefinition, Object[] args) throws BeanCreationException {(3注)
… …
//正常的bean实例化,实例化后的样子:
//BeanWrapperImpl:wrappingclass[org.springframework.
//samples.jpetstore.service.UserManagerImpl]
instanceWrapper = createBeanInstance(beanName, mergedBeanDefinition, args);
//AOP的部分来了,不过前提是这个bean设置了AOP属性
//既某个BeanPostProcessor的bean引用了它
bean = initializeBean(beanName, bean, mergedBeanDefinition); (4)
… …
}
(4注)
protected Object initializeBean(String beanName, Object bean, RootBeanDefinition
mergedBeanDefinition) throws BeansException {
… …
if (mergedBeanDefinition == null || !mergedBeanDefinition.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean,
beanName); (5)
}
return wrappedBean;
}
(5注)
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String
beanName) throws BeansException {
Object result = existingBean;
//找到所有已经注册的类型为BeanPostProcessor的bean
//具体的注册过程请参见
// Inside-springframework-Loader-registerBeanPostProcessors
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
//经过处理后返回的是一个JdkDynamicAopProxy对象
result = beanProcessor.postProcessAfterInitialization(result, beanName);(5)
}
return result;
}
}
(5注)
★ public abstract class AbstractAutoProxyCreator extends ProxyConfig
implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Ordered {
public Object postProcessAfterInitialization(Object bean, String beanName) throws
BeansException {
if (this.targetSourcedBeanNames.contains(beanName) ||
isInfrastructureClass(bean.getClass(), beanName) ||
shouldSkip(bean.getClass(), beanName))
{
return bean;
}
// Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(),
beanName, null); (7)
if (specificInterceptors != DO_NOT_PROXY) {
//本来是实例化一个不同的bean,经过这一步后返回一个Proxy对象
return createProxy(bean.getClass(), beanName, specificInterceptors, new
SingletonTargetSource(bean));(8)
}
… …
}
(8注)
protected Object createProxy(
Class beanClass, String beanName, Object[] specificInterceptors,
TargetSource targetSource) {
//呵呵,见到ProxyFactory了
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this); (9)
if (!isProxyTargetClass()) {
// Must allow for introductions; can't just set interfaces to
// the target's interfaces only.
//sample: UserManager、Manager
Class[] targetsInterfaces = ClassUtils.getAllInterfacesForClass(beanClass);
for (int i = 0; i < targetsInterfaces.length; i++) {
proxyFactory.addInterface(targetsInterfaces[i]);
}
}
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); (10)
for (int i = 0; i < advisors.length; i++) {
proxyFactory.addAdvisor(advisors[i]);
}
//example: targetSource = UserManagerImpl
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
return proxyFactory.getProxy(); (11)
}
protected Advisor[] buildAdvisors(String beanName, Object[] specificInterceptors) {(10注)
Advisor[] commonInterceptors = resolveInterceptorNames();
List allInterceptors = new ArrayList();
if (specificInterceptors != null) {
allInterceptors.addAll(Arrays.asList(specificInterceptors));
if (commonInterceptors != null) {
if (this.applyCommonInterceptorsFirst) {
//处理Interceptor
//sample:[org.springframework.aop.support.
//RegexpMethodPointcutAdvisor: advice
//[org.springframework.aop.interceptor.
//cache.OSCacheInterceptor@1978933], //pointcut patterns
//{.*getAllUsers, .*getUserByUsername}]
allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
}
else {
allInterceptors.addAll(Arrays.asList(commonInterceptors));
}
}
}
}
private Advisor[] resolveInterceptorNames() {
List advisors = new ArrayList();
for (int i = 0; i < this.interceptorNames.length; i++) {
//sample: userManagerAdvisor
String beanName = this.interceptorNames[i];
if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
//实例化advisor
//sample:next=org.springframework.aop.support.
//RegexpMethodPointcutAdvisor: advice
//[org.springframework.aop.interceptor.cache.
//OSCacheInte rceptor@1978933], pointcut patterns
//{.*getAllUsers, .*getUserByUsername}
Object next = this.beanFactory.getBean(beanName);
advisors.add(this.advisorAdapterRegistry.wrap(next));
return (Advisor[]) advisors.toArray(new Advisor[advisors.size()]);
}
}
}
}
★ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) { (7注)
//这里的beanNames在Inside-springframework-Loader-registerBeanPostProcessors
//中设置
//配置文件的配置如下
// <bean id="userManagerCacheProxyCreator" class=”… …”>
// <property name="beanNames"><value>userManager</value></property>
// </bean>
if (this.beanNames != null) {
for (Iterator it = this.beanNames.iterator(); it.hasNext();) {
// mappedName= userManager
String mappedName = (String) it.next();
if (isMatch(beanName, mappedName)) {
// protected static final Object[]
//PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0];
return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
}
}
}
}
}
★public class ProxyConfig implements Serializable {(9注)
public void copyFrom(ProxyConfig other) {
this.proxyTargetClass = other.proxyTargetClass;
this.optimize = other.optimize;
this.exposeProxy = other.exposeProxy;
this.frozen = other.frozen;
this.opaque = other.opaque;
this.aopProxyFactory = other.aopProxyFactory;
}
}
★ public abstract class AbstractAutoProxyCreator extends ProxyConfig
implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Ordered {
}
(11注)
★ public class ProxyFactory extends AdvisedSupport implements AopProxy {
public Object getProxy() {
return createAopProxy().getProxy(); (12)
}
}
★ public class AdvisedSupport extends ProxyConfig implements Advised {
protected synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this); (13)
}
}
★ public class DefaultAopProxyFactory implements AopProxyFactory {
public AopProxy createAopProxy(AdvisedSupport advisedSupport) throws AopConfigException {
if (advisedSupport.isOptimize() || advisedSupport.isProxyTargetClass() ||
hasNoUserSuppliedProxyInterfaces(advisedSupport)) {
if (!cglibAvailable) {
throw new AopConfigException(
"Cannot proxy target class because CGLIB2 is not available. " +
"Add CGLIB to the class path or specify proxy interfaces.");
}
return CglibProxyFactory.createCglibProxy(advisedSupport);
}
else {
//呵呵,万变不离其踪,熟悉的java动态代理来了
return new JdkDynamicAopProxy(advisedSupport);(14)
}
}
}
★ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
… …
this.advised = config;
}
//invoke传入被代理对象的方法名称和执行参数
//可以在invoke前后加上操作,
//method.invoke传回的对象是实际方法执行后的传回对象
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
}
(12注)
public Object getProxy(ClassLoader classLoader) {
Class[] proxiedInterfaces =
AopProxyUtils.completeProxiedInterfaces(this.advised);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
//标准的java动态代理动作,注册代理对象,注册要代理对象的接口
//example: proxiedInterfaces=
//[interface org.springframework.samples.jpetstore.
//service.UserManager, interface
//org.springframework.samples.
//jpetstore.service.Manager, interface
//org.springframework.aop.SpringProxy,
//interface //org.springframework.aop.framework.Advised]
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
}
Note:
Config= org.springframework.aop.framework.ProxyFactory: 2 interfaces [org.springframework.samples.jpetstore.service.UserManager, org.springframework.samples.jpetstore.service.Manager]; 1 advisors [org.springframework.aop.support.RegexpMethodPointcutAdvisor: advice [org.springframework.aop.interceptor.cache.OSCacheInterceptor@7981d5], pointcut patterns {.*getAllUsers, .*getUserByUsername}]; targetSource [SingletonTargetSource for target: org.springframework.samples.jpetstore.service.UserManagerImpl@2ee7e5]; advisorChainFactory [org.springframework.aop.framework.HashMapCachingAdvisorChainFactory@17aaa0e]; proxyTargetClass=false; optimize=false; exposeProxy=false; opaque=false; frozen=false; aopProxyFactory [org.springframework.aop.framework.DefaultAopProxyFactory@eff545]
- Inside-springframework-AOP-creator
- Inside-springframework-AOP-invoke
- Inside-springframework-Loader-registerBeanPostProcessors
- Inside-springframework-bean-definition
- Inside-springframework-XmlWebApplicationContext
- Inside-springframework-proxy
- Inside-springframework-JdkDynamicAopProxy
- Inside-springframework-BeanDefinition
- Inside-springframework-ContextLoaderListener
- SpringFramework中的AOP简单使用
- SpringFramework中的AOP简单使用
- SpringFramework中的AOP简单使用
- SpringFramework中的AOP简单使用
- SpringFramework中的AOP简单使用
- SpringFramework中的AOP简单使用
- SpringFramework中的AOP简单使用
- org.springframework.aop Interface ThrowsAdvice
- AOP实现机制AspectJ和SpringFramework
- Windows Vista 开发新特性(2)- 你的文件存在哪?
- 应用总结:ASP编程心得回放
- 创建DataGrid并响应了CheckBox事件
- Mantis中文问题的解决办法
- 把木梳卖给和尚
- Inside-springframework-AOP-creator
- 请教各位大虾我的C程序哪里有错!急!!!
- Asp无组件生成缩略图
- Inside-springframework-AOP-invoke
- java面试题答案
- Inside-springframework-Loader-registerBeanPostProcessors
- 软件测试内容全貌——全景图 (1)
- Inside-springframework-bean-definition
- 用文本+ASP打造新闻发布系统