(转)
2012/1/3 by tony
接着上次的讲,以下这个sample
- package com.hyron.tony;
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.core.io.ClassPathResource;
-
- public class Test {
-
- public static void main(String[] args)throws Exception {
- BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
- GreetingService greetingService = (GreetingService)factory.getBean("greetingService");
- greetingService.sayGreeting();
- }
-
- }
Bean的实时启动,就是以下这行代码:
- (GreetingService)factory.getBean("greetingService");
他的执行树如下:
Factory.getBean
-- XmlBeanFactory
--AbstractAutowireCapableBeanFactory
-- AbstractBeanFactory 在其中找到如下方法
-
-
-
-
- public Object getBean(String name) throws BeansException {
- return doGetBean(name, null, null, false);
- }
doGetBean的方法声明:
-
-
-
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- protected <T> T doGetBean(
- final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
- throws BeansException {
- }
我真觉得有时候研究人家代码真不如看人家注释,特别是很好的开源架构,代码是好得很
doGetBean方法中比较有意思的代码如下:
//将beanName前面可能的&符号滤掉
- final String beanName = transformedBeanName(name);
//得到已经登记过的单例Object,而不是再次生成它
- Object sharedInstance = getSingleton(beanName);
它的具体代码如下:
-
-
-
-
-
-
-
-
- protected Object getSingleton(String beanName, boolean allowEarlyReference) {
- Object singletonObject = this.singletonObjects.get(beanName);
- if (singletonObject == null) {
- synchronized (this.singletonObjects) {
- singletonObject = this.earlySingletonObjects.get(beanName);
- if (singletonObject == null && allowEarlyReference) {
- ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
- if (singletonFactory != null) {
- singletonObject = singletonFactory.getObject();
- this.earlySingletonObjects.put(beanName, singletonObject);
- this.singletonFactories.remove(beanName);
- }
- }
- }
- }
- return (singletonObject != NULL_OBJECT ? singletonObject : null);
- }
其中有一点比较有意思,就是singletonFactories是在哪里塞入的
以下:
-
-
-
-
-
-
-
-
- protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) {
- Assert.notNull(singletonFactory, "Singleton factory must not be null");
- synchronized (this.singletonObjects) {
- if (!this.singletonObjects.containsKey(beanName)) {
- this.singletonFactories.put(beanName, singletonFactory);
- this.earlySingletonObjects.remove(beanName);
- this.registeredSingletons.add(beanName);
- }
- }
- }
这个方法被执行与createBean
createBean的执行其实是在doGetBean方法内本身
接下来从一个BeanFactory中获得对象的instance
-
-
-
-
-
-
-
-
-
- protected Object getObjectForBeanInstance(
- Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
-
-
- if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
- throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
- }
-
-
-
-
- if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
- return beanInstance;
- }
-
- Object object = null;
- if (mbd == null) {
- object = getCachedObjectForFactoryBean(beanName);
- }
- if (object == null) {
-
- FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
-
- if (mbd == null && containsBeanDefinition(beanName)) {
- mbd = getMergedLocalBeanDefinition(beanName);
- }
- boolean synthetic = (mbd != null && mbd.isSynthetic());
- object = getObjectFromFactoryBean(factory, beanName, !synthetic);
- }
- return object;
- }
否则的话,失败的话,则从BeanFacory中动态生成对象实例
-
-
- if (isPrototypeCurrentlyInCreation(beanName)) {
- throw new BeanCurrentlyInCreationException(beanName);
- }
-
-
- BeanFactory parentBeanFactory = getParentBeanFactory();
- if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
-
- String nameToLookup = originalBeanName(name);
- if (args != null) {
-
- return (T) parentBeanFactory.getBean(nameToLookup, args);
- }
- else {
-
- return parentBeanFactory.getBean(nameToLookup, requiredType);
- }
- }
以上这段代码真的很让人费解,什么是BeanFactory,什么是FactoryBean
接下来,如果在失败,就直接createBean
-
- if (mbd.isSingleton()) {
- sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
- public Object getObject() throws BeansException {
- try {
- return createBean(beanName, mbd, args);
- }
- catch (BeansException ex) {
-
-
-
- destroySingleton(beanName);
- throw ex;
- }
- }
- });
- bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
- }
其中createBean是写在父类中的抽象类 AbstractAutowireCapableBeanFactory中
-
-
-
-
-
- @Override
- protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
- throws BeanCreationException {
-
- if (logger.isDebugEnabled()) {
- logger.debug("Creating instance of bean '" + beanName + "'");
- }
-
- resolveBeanClass(mbd, beanName);
-
-
- try {
- mbd.prepareMethodOverrides();
- }
- catch (BeanDefinitionValidationException ex) {
- throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
- beanName, "Validation of method overrides failed", ex);
- }
-
- try {
-
- Object bean = resolveBeforeInstantiation(beanName, mbd);
- if (bean != null) {
- return bean;
- }
- }
- catch (Throwable ex) {
- throw new BeanCreationException(mbd.getResourceDescription(), beanName,
- "BeanPostProcessor before instantiation of bean failed", ex);
- }
-
- Object beanInstance = doCreateBean(beanName, mbd, args);
- if (logger.isDebugEnabled()) {
- logger.debug("Finished creating instance of bean '" + beanName + "'");
- }
- return beanInstance;
- }
其中真正反射生成对象instance的是
- protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
这个方法分成两部分:
第一,生成对象instance的Wapper,用到了包装者模式
- if (instanceWrapper == null) {
- instanceWrapper = createBeanInstance(beanName, mbd, args);
- }
第二,实例化对象instance
-
- Object exposedObject = bean;
- try {
- populateBean(beanName, mbd, instanceWrapper);
- if (exposedObject != null) {
- exposedObject = initializeBean(beanName, exposedObject, mbd);
- }
- }
- catch (Throwable ex) {
- if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
- throw (BeanCreationException) ex;
- }
- else {
- throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
- }
- }
其中createBeanInstance中最简单的生成期是
-
- return instantiateBean(beanName, mbd);
它的核心代码:
- if (System.getSecurityManager() != null) {
- beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- return getInstantiationStrategy().instantiate(mbd, beanName, parent);
- }
- }, getAccessControlContext());
- }
- else {
- beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
- }
这里使用了策略模式,将实际的算法放到策略接口中去
一般最简单的实现的策略模式就是:
-
-
-
-
-
-
-
-
-
-
-
-
- public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
-
-
-
-
-
-
-
-
-
- public Object instantiate(Constructor ctor, Object[] args) {
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(this.beanDefinition.getBeanClass());
- enhancer.setCallbackFilter(new CallbackFilterImpl());
- enhancer.setCallbacks(new Callback[] {
- NoOp.INSTANCE,
- new LookupOverrideMethodInterceptor(),
- new ReplaceOverrideMethodInterceptor()
- });
-
- return (ctor == null) ?
- enhancer.create() :
- enhancer.create(ctor.getParameterTypes(), args);
- }
真正最终的对象生成器是
- net.sf.cglib.proxy.Enhancer;
spring没有用原生态的代理反射,而是用这个开源jar包来实现了动态生成
最后spring对对象的实例化,和参数的注入,是以下代码:
-
-
-
-
-
-
-
- protected void populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw) {
- PropertyValues pvs = mbd.getPropertyValues();
-
- if (bw == null) {
- if (!pvs.isEmpty()) {
- throw new BeanCreationException(
- mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
- }
- else {
-
- return;
- }
- }
-
-
-
-
- boolean continueWithPropertyPopulation = true;
-
- if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
- for (BeanPostProcessor bp : getBeanPostProcessors()) {
- if (bp instanceof InstantiationAwareBeanPostProcessor) {
- InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
- if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
- continueWithPropertyPopulation = false;
- break;
- }
- }
- }
- }
-
- if (!continueWithPropertyPopulation) {
- return;
- }
-
- if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
- mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
- MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
-
-
- if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
- autowireByName(beanName, mbd, bw, newPvs);
- }
-
-
- if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
- autowireByType(beanName, mbd, bw, newPvs);
- }
-
- pvs = newPvs;
- }
-
- boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
- boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
-
- if (hasInstAwareBpps || needsDepCheck) {
- PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw);
- if (hasInstAwareBpps) {
- for (BeanPostProcessor bp : getBeanPostProcessors()) {
- if (bp instanceof InstantiationAwareBeanPostProcessor) {
- InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
- pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
- if (pvs == null) {
- return;
- }
- }
- }
- }
- if (needsDepCheck) {
- checkDependencies(beanName, mbd, filteredPds, pvs);
- }
- }
-
- applyPropertyValues(beanName, mbd, bw, pvs);
- }
我真不知道这些代码是怎么写出来的。
怎么能这么牛,有时候看到这些浩如烟海的牛逼的代码,真是觉得自己和人家比起来,技术的道路算是到头了。
这些人真是他妈的天才。
附:cglib的简单介绍:
http://java.csecs.com/posts/list/1633.html
http://www.blogjava.net/stone2083/archive/2008/03/16/186615.html
http://www.blogjava.net/georgehill/archive/2005/05/24/5126.html