Spring 学习记录5 BeanFactory

主题

记录我对BeanFactor接口的简单的学习.

BeanFactory我感觉就是管理bean用的容器,持有一堆的bean,你可以get各种bean.然后也提供一些bean相关的功能比如别名呀之类的..

 

结构

Spring 学习记录5 BeanFactory_第1张图片

我觉得核心功能都写在了3个子接口里面了.

小实验:

 1     /**
 2      * 测试BeanFactory
 3      */
 4     @Test
 5     public void testBeanFactory() {
 6         BeanFactory beanFactory = this.applicationContext;
 7         System.out.println(beanFactory.getBean("myBeanFactoryTestBean")); // spring.BeanFactoryTest@484b2882
 8 
 9         System.out.println(beanFactory.getBean(Environment.class)); // StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[systemProperties,systemEnvironment,class path resource [test.properties]]}
10 
11         System.out.println(beanFactory.getBean("myFactoryBean-1")); // java.lang.Object@327ac9a7
12         System.out.println(beanFactory.getBean("myFactoryBean-1")); // java.lang.Object@5f8581f3
13         System.out.println(beanFactory.isSingleton("myFactoryBean-1")); // false
14         System.out.println(beanFactory.getBean("&myFactoryBean-1")); // spring.MyFactoryBean@1b4d0cd5 &开头的是FactoryBean
15         System.out.println(beanFactory.isSingleton("&myFactoryBean-1")); // true
16 
17         // System.out.println(beanFactory.getBean("not exists bean")); // 异常
18     }

 

 

HierarchicalBeanFactory

 1 /*
 2  * Copyright 2002-2012 the original author or authors.
 3  *
 4  * Licensed under the Apache License, Version 2.0 (the "License");
 5  * you may not use this file except in compliance with the License.
 6  * You may obtain a copy of the License at
 7  *
 8  *      http://www.apache.org/licenses/LICENSE-2.0
 9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package org.springframework.beans.factory;
18 
19 /**
20  * Sub-interface implemented by bean factories that can be part
21  * of a hierarchy.
22  *
23  * 

The corresponding {@code setParentBeanFactory} method for bean 24 * factories that allow setting the parent in a configurable 25 * fashion can be found in the ConfigurableBeanFactory interface. 26 * 27 * @author Rod Johnson 28 * @author Juergen Hoeller 29 * @since 07.07.2003 30 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setParentBeanFactory 31 */ 32 public interface HierarchicalBeanFactory extends BeanFactory { 33 34 /** 35 * Return the parent bean factory, or {@code null} if there is none. 36 */ 37 BeanFactory getParentBeanFactory(); 38 39 /** 40 * Return whether the local bean factory contains a bean of the given name, 41 * ignoring beans defined in ancestor contexts. 42 *

This is an alternative to {@code containsBean}, ignoring a bean 43 * of the given name from an ancestor bean factory. 44 * @param name the name of the bean to query 45 * @return whether a bean with the given name is defined in the local factory 46 * @see BeanFactory#containsBean 47 */ 48 boolean containsLocalBean(String name); 49 50 }

View Code

这个接口还是比较简单的,从这个接口中我们可以学习到BeanFactory是可以有层级的.

getParentBeanFactory方法可以获取父级BeanFactory

containsLocalBean方法用途判断当前这个beanFactory是否包含需要的bean

如果要从当前BF或者祖先BF里获取bean可以使用Spring的1个Utils叫做BeanFactoryUtils来帮忙..它里面很多方法都是XXXXIncludingAncestors这些方法不光从本BF中找bean,还可以遍历祖先BF.

 

ListableBeanFactory

  1 /*
  2  * Copyright 2002-2013 the original author or authors.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package org.springframework.beans.factory;
 18 
 19 import java.lang.annotation.Annotation;
 20 import java.util.Map;
 21 
 22 import org.springframework.beans.BeansException;
 23 
 24 /**
 25  * Extension of the {@link BeanFactory} interface to be implemented by bean factories
 26  * that can enumerate all their bean instances, rather than attempting bean lookup
 27  * by name one by one as requested by clients. BeanFactory implementations that
 28  * preload all their bean definitions (such as XML-based factories) may implement
 29  * this interface.
 30  *
 31  * 

If this is a {@link HierarchicalBeanFactory}, the return values will not 32 * take any BeanFactory hierarchy into account, but will relate only to the beans 33 * defined in the current factory. Use the {@link BeanFactoryUtils} helper class 34 * to consider beans in ancestor factories too. 35 * 36 *

The methods in this interface will just respect bean definitions of this factory. 37 * They will ignore any singleton beans that have been registered by other means like 38 * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}'s 39 * {@code registerSingleton} method, with the exception of 40 * {@code getBeanNamesOfType} and {@code getBeansOfType} which will check 41 * such manually registered singletons too. Of course, BeanFactory's {@code getBean} 42 * does allow transparent access to such special beans as well. However, in typical 43 * scenarios, all beans will be defined by external bean definitions anyway, so most 44 * applications don't need to worry about this differentiation. 45 * 46 *

NOTE: With the exception of {@code getBeanDefinitionCount} 47 * and {@code containsBeanDefinition}, the methods in this interface 48 * are not designed for frequent invocation. Implementations may be slow. 49 * 50 * @author Rod Johnson 51 * @author Juergen Hoeller 52 * @since 16 April 2001 53 * @see HierarchicalBeanFactory 54 * @see BeanFactoryUtils 55 */ 56 public interface ListableBeanFactory extends BeanFactory { 57 58 /** 59 * Check if this bean factory contains a bean definition with the given name. 60 *

Does not consider any hierarchy this factory may participate in, 61 * and ignores any singleton beans that have been registered by 62 * other means than bean definitions. 63 * @param beanName the name of the bean to look for 64 * @return if this bean factory contains a bean definition with the given name 65 * @see #containsBean 66 */ 67 boolean containsBeanDefinition(String beanName); 68 69 /** 70 * Return the number of beans defined in the factory. 71 *

Does not consider any hierarchy this factory may participate in, 72 * and ignores any singleton beans that have been registered by 73 * other means than bean definitions. 74 * @return the number of beans defined in the factory 75 */ 76 int getBeanDefinitionCount(); 77 78 /** 79 * Return the names of all beans defined in this factory. 80 *

Does not consider any hierarchy this factory may participate in, 81 * and ignores any singleton beans that have been registered by 82 * other means than bean definitions. 83 * @return the names of all beans defined in this factory, 84 * or an empty array if none defined 85 */ 86 String[] getBeanDefinitionNames(); 87 88 /** 89 * Return the names of beans matching the given type (including subclasses), 90 * judging from either bean definitions or the value of {@code getObjectType} 91 * in the case of FactoryBeans. 92 *

NOTE: This method introspects top-level beans only. It does not 93 * check nested beans which might match the specified type as well. 94 *

Does consider objects created by FactoryBeans, which means that FactoryBeans 95 * will get initialized. If the object created by the FactoryBean doesn't match, 96 * the raw FactoryBean itself will be matched against the type. 97 *

Does not consider any hierarchy this factory may participate in. 98 * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors} 99 * to include beans in ancestor factories too. 100 *

Note: Does not ignore singleton beans that have been registered 101 * by other means than bean definitions. 102 *

This version of {@code getBeanNamesForType} matches all kinds of beans, 103 * be it singletons, prototypes, or FactoryBeans. In most implementations, the 104 * result will be the same as for {@code getBeanNamesForType(type, true, true)}. 105 *

Bean names returned by this method should always return bean names in the 106 * order of definition in the backend configuration, as far as possible. 107 * @param type the class or interface to match, or {@code null} for all bean names 108 * @return the names of beans (or objects created by FactoryBeans) matching 109 * the given object type (including subclasses), or an empty array if none 110 * @see FactoryBean#getObjectType 111 * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class) 112 */ 113 String[] getBeanNamesForType(Class type); 114 115 /** 116 * Return the names of beans matching the given type (including subclasses), 117 * judging from either bean definitions or the value of {@code getObjectType} 118 * in the case of FactoryBeans. 119 *

NOTE: This method introspects top-level beans only. It does not 120 * check nested beans which might match the specified type as well. 121 *

Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, 122 * which means that FactoryBeans will get initialized. If the object created by the 123 * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the 124 * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked 125 * (which doesn't require initialization of each FactoryBean). 126 *

Does not consider any hierarchy this factory may participate in. 127 * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors} 128 * to include beans in ancestor factories too. 129 *

Note: Does not ignore singleton beans that have been registered 130 * by other means than bean definitions. 131 *

Bean names returned by this method should always return bean names in the 132 * order of definition in the backend configuration, as far as possible. 133 * @param type the class or interface to match, or {@code null} for all bean names 134 * @param includeNonSingletons whether to include prototype or scoped beans too 135 * or just singletons (also applies to FactoryBeans) 136 * @param allowEagerInit whether to initialize lazy-init singletons and 137 * objects created by FactoryBeans (or by factory methods with a 138 * "factory-bean" reference) for the type check. Note that FactoryBeans need to be 139 * eagerly initialized to determine their type: So be aware that passing in "true" 140 * for this flag will initialize FactoryBeans and "factory-bean" references. 141 * @return the names of beans (or objects created by FactoryBeans) matching 142 * the given object type (including subclasses), or an empty array if none 143 * @see FactoryBean#getObjectType 144 * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean) 145 */ 146 String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit); 147 148 /** 149 * Return the bean instances that match the given object type (including 150 * subclasses), judging from either bean definitions or the value of 151 * {@code getObjectType} in the case of FactoryBeans. 152 *

NOTE: This method introspects top-level beans only. It does not 153 * check nested beans which might match the specified type as well. 154 *

Does consider objects created by FactoryBeans, which means that FactoryBeans 155 * will get initialized. If the object created by the FactoryBean doesn't match, 156 * the raw FactoryBean itself will be matched against the type. 157 *

Does not consider any hierarchy this factory may participate in. 158 * Use BeanFactoryUtils' {@code beansOfTypeIncludingAncestors} 159 * to include beans in ancestor factories too. 160 *

Note: Does not ignore singleton beans that have been registered 161 * by other means than bean definitions. 162 *

This version of getBeansOfType matches all kinds of beans, be it 163 * singletons, prototypes, or FactoryBeans. In most implementations, the 164 * result will be the same as for {@code getBeansOfType(type, true, true)}. 165 *

The Map returned by this method should always return bean names and 166 * corresponding bean instances in the order of definition in the 167 * backend configuration, as far as possible. 168 * @param type the class or interface to match, or {@code null} for all concrete beans 169 * @return a Map with the matching beans, containing the bean names as 170 * keys and the corresponding bean instances as values 171 * @throws BeansException if a bean could not be created 172 * @since 1.1.2 173 * @see FactoryBean#getObjectType 174 * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) 175 */ 176 Map getBeansOfType(Class type) throws BeansException; 177 178 /** 179 * Return the bean instances that match the given object type (including 180 * subclasses), judging from either bean definitions or the value of 181 * {@code getObjectType} in the case of FactoryBeans. 182 *

NOTE: This method introspects top-level beans only. It does not 183 * check nested beans which might match the specified type as well. 184 *

Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, 185 * which means that FactoryBeans will get initialized. If the object created by the 186 * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the 187 * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked 188 * (which doesn't require initialization of each FactoryBean). 189 *

Does not consider any hierarchy this factory may participate in. 190 * Use BeanFactoryUtils' {@code beansOfTypeIncludingAncestors} 191 * to include beans in ancestor factories too. 192 *

Note: Does not ignore singleton beans that have been registered 193 * by other means than bean definitions. 194 *

The Map returned by this method should always return bean names and 195 * corresponding bean instances in the order of definition in the 196 * backend configuration, as far as possible. 197 * @param type the class or interface to match, or {@code null} for all concrete beans 198 * @param includeNonSingletons whether to include prototype or scoped beans too 199 * or just singletons (also applies to FactoryBeans) 200 * @param allowEagerInit whether to initialize lazy-init singletons and 201 * objects created by FactoryBeans (or by factory methods with a 202 * "factory-bean" reference) for the type check. Note that FactoryBeans need to be 203 * eagerly initialized to determine their type: So be aware that passing in "true" 204 * for this flag will initialize FactoryBeans and "factory-bean" references. 205 * @return a Map with the matching beans, containing the bean names as 206 * keys and the corresponding bean instances as values 207 * @throws BeansException if a bean could not be created 208 * @see FactoryBean#getObjectType 209 * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean) 210 */ 211 Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) 212 throws BeansException; 213 214 /** 215 * Find all names of beans whose {@code Class} has the supplied {@link Annotation} 216 * type, without creating any bean instances yet. 217 * @param annotationType the type of annotation to look for 218 * @return the names of all matching beans 219 * @since 4.0 220 */ 221 String[] getBeanNamesForAnnotation(Classextends Annotation> annotationType); 222 223 /** 224 * Find all beans whose {@code Class} has the supplied {@link Annotation} type, 225 * returning a Map of bean names with corresponding bean instances. 226 * @param annotationType the type of annotation to look for 227 * @return a Map with the matching beans, containing the bean names as 228 * keys and the corresponding bean instances as values 229 * @throws BeansException if a bean could not be created 230 * @since 3.0 231 */ 232 Map getBeansWithAnnotation(Classextends Annotation> annotationType) throws BeansException; 233 234 /** 235 * Find an {@link Annotation} of {@code annotationType} on the specified 236 * bean, traversing its interfaces and super classes if no annotation can be 237 * found on the given class itself. 238 * @param beanName the name of the bean to look for annotations on 239 * @param annotationType the annotation class to look for 240 * @return the annotation of the given type if found, or {@code null} 241 * @throws NoSuchBeanDefinitionException if there is no bean with the given name 242 * @since 3.0 243 */ 244 extends Annotation> A findAnnotationOnBean(String beanName, Class annotationType) 245 throws NoSuchBeanDefinitionException; 246 247 }

View Code

这个接口给予了批量获取bean的能力,一般的BF只能获取单个bean,但是这个接口可以获取满足条件的一堆bean.

我觉得用的比较多的可能是

 Map getBeansOfType(Class type) throws BeansException;

Map getBeansWithAnnotation(Classextends Annotation> annotationType) throws BeansException;

这2个方法..

如果自己的bean有一些地方要特殊处理的.可能会自己写1个bean实现InitializingBean接口在afterPropertiesSet方法里通过这个接口取出所有bean然后去遍历,找到你要的bean然后再做特殊处理.

 

小实验:

 1     /**
 2      * ListableBeanFactory HierarchicalBeanFactory 测试
 3      */
 4     @Test
 5     public void testListableBeanFactoryAndHierarchicalBeanFactory() {
 6         // ListableBeanFactory里的方法不会考虑parent里的bean
 7         DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) this.applicationContext.getAutowireCapableBeanFactory(); // DefaultListableBeanFactory
 8         DefaultListableBeanFactory child = new DefaultListableBeanFactory();
 9         child.setParentBeanFactory(beanFactory); // 设置
10 
11         System.out.println(child.getBeansOfType(BeanFactoryTest.class)); // {}
12         System.out.println(child.containsLocalBean("myBeanFactoryTestBean")); // false
13         System.out.println(child.containsBean("myBeanFactoryTestBean")); // true
14         System.out.println(BeanFactoryUtils.beansOfTypeIncludingAncestors(child, BeanFactoryTest.class)); // {myBeanFactoryTestBean=spring.BeanFactoryTest@3616a983}
15 
16         System.out.println(child.getBeansWithAnnotation(RunWith.class)); // {}
17         System.out.println(beanFactory.getBeansWithAnnotation(RunWith.class)); // {myBeanFactoryTestBean=spring.BeanFactoryTest@3616a983}
18     }

 

AutowireCapableBeanFactory

  1 /*
  2  * Copyright 2002-2013 the original author or authors.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package org.springframework.beans.factory.config;
 18 
 19 import java.util.Set;
 20 
 21 import org.springframework.beans.BeansException;
 22 import org.springframework.beans.TypeConverter;
 23 import org.springframework.beans.factory.BeanFactory;
 24 
 25 /**
 26  * Extension of the {@link org.springframework.beans.factory.BeanFactory}
 27  * interface to be implemented by bean factories that are capable of
 28  * autowiring, provided that they want to expose this functionality for
 29  * existing bean instances.
 30  *
 31  * 

This subinterface of BeanFactory is not meant to be used in normal 32 * application code: stick to {@link org.springframework.beans.factory.BeanFactory} 33 * or {@link org.springframework.beans.factory.ListableBeanFactory} for 34 * typical use cases. 35 * 36 *

Integration code for other frameworks can leverage this interface to 37 * wire and populate existing bean instances that Spring does not control 38 * the lifecycle of. This is particularly useful for WebWork Actions and 39 * Tapestry Page objects, for example. 40 * 41 *

Note that this interface is not implemented by 42 * {@link org.springframework.context.ApplicationContext} facades, 43 * as it is hardly ever used by application code. That said, it is available 44 * from an application context too, accessible through ApplicationContext's 45 * {@link org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()} 46 * method. 47 * 48 *

You may also implement the {@link org.springframework.beans.factory.BeanFactoryAware} 49 * interface, which exposes the internal BeanFactory even when running in an 50 * ApplicationContext, to get access to an AutowireCapableBeanFactory: 51 * simply cast the passed-in BeanFactory to AutowireCapableBeanFactory. 52 * 53 * @author Juergen Hoeller 54 * @since 04.12.2003 55 * @see org.springframework.beans.factory.BeanFactoryAware 56 * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory 57 * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory() 58 */ 59 public interface AutowireCapableBeanFactory extends BeanFactory { 60 61 /** 62 * Constant that indicates no externally defined autowiring. Note that 63 * BeanFactoryAware etc and annotation-driven injection will still be applied. 64 * @see #createBean 65 * @see #autowire 66 * @see #autowireBeanProperties 67 */ 68 int AUTOWIRE_NO = 0; 69 70 /** 71 * Constant that indicates autowiring bean properties by name 72 * (applying to all bean property setters). 73 * @see #createBean 74 * @see #autowire 75 * @see #autowireBeanProperties 76 */ 77 int AUTOWIRE_BY_NAME = 1; 78 79 /** 80 * Constant that indicates autowiring bean properties by type 81 * (applying to all bean property setters). 82 * @see #createBean 83 * @see #autowire 84 * @see #autowireBeanProperties 85 */ 86 int AUTOWIRE_BY_TYPE = 2; 87 88 /** 89 * Constant that indicates autowiring the greediest constructor that 90 * can be satisfied (involves resolving the appropriate constructor). 91 * @see #createBean 92 * @see #autowire 93 */ 94 int AUTOWIRE_CONSTRUCTOR = 3; 95 96 /** 97 * Constant that indicates determining an appropriate autowire strategy 98 * through introspection of the bean class. 99 * @see #createBean 100 * @see #autowire 101 * @deprecated as of Spring 3.0: If you are using mixed autowiring strategies, 102 * prefer annotation-based autowiring for clearer demarcation of autowiring needs. 103 */ 104 @Deprecated 105 int AUTOWIRE_AUTODETECT = 4; 106 107 108 //------------------------------------------------------------------------- 109 // Typical methods for creating and populating external bean instances 110 //------------------------------------------------------------------------- 111 112 /** 113 * Fully create a new bean instance of the given class. 114 *

Performs full initialization of the bean, including all applicable 115 * {@link BeanPostProcessor BeanPostProcessors}. 116 *

Note: This is intended for creating a fresh instance, populating annotated 117 * fields and methods as well as applying all standard bean initialiation callbacks. 118 * It does not imply traditional by-name or by-type autowiring of properties; 119 * use {@link #createBean(Class, int, boolean)} for that purposes. 120 * @param beanClass the class of the bean to create 121 * @return the new bean instance 122 * @throws BeansException if instantiation or wiring failed 123 */ 124 T createBean(Class beanClass) throws BeansException; 125 126 /** 127 * Populate the given bean instance through applying after-instantiation callbacks 128 * and bean property post-processing (e.g. for annotation-driven injection). 129 *

Note: This is essentially intended for (re-)populating annotated fields and 130 * methods, either for new instances or for deserialized instances. It does 131 * not imply traditional by-name or by-type autowiring of properties; 132 * use {@link #autowireBeanProperties} for that purposes. 133 * @param existingBean the existing bean instance 134 * @throws BeansException if wiring failed 135 */ 136 void autowireBean(Object existingBean) throws BeansException; 137 138 /** 139 * Configure the given raw bean: autowiring bean properties, applying 140 * bean property values, applying factory callbacks such as {@code setBeanName} 141 * and {@code setBeanFactory}, and also applying all bean post processors 142 * (including ones which might wrap the given raw bean). 143 *

This is effectively a superset of what {@link #initializeBean} provides, 144 * fully applying the configuration specified by the corresponding bean definition. 145 * Note: This method requires a bean definition for the given name! 146 * @param existingBean the existing bean instance 147 * @param beanName the name of the bean, to be passed to it if necessary 148 * (a bean definition of that name has to be available) 149 * @return the bean instance to use, either the original or a wrapped one 150 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException 151 * if there is no bean definition with the given name 152 * @throws BeansException if the initialization failed 153 * @see #initializeBean 154 */ 155 Object configureBean(Object existingBean, String beanName) throws BeansException; 156 157 /** 158 * Resolve the specified dependency against the beans defined in this factory. 159 * @param descriptor the descriptor for the dependency 160 * @param beanName the name of the bean which declares the present dependency 161 * @return the resolved object, or {@code null} if none found 162 * @throws BeansException in dependency resolution failed 163 */ 164 Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException; 165 166 167 //------------------------------------------------------------------------- 168 // Specialized methods for fine-grained control over the bean lifecycle 169 //------------------------------------------------------------------------- 170 171 /** 172 * Fully create a new bean instance of the given class with the specified 173 * autowire strategy. All constants defined in this interface are supported here. 174 *

Performs full initialization of the bean, including all applicable 175 * {@link BeanPostProcessor BeanPostProcessors}. This is effectively a superset 176 * of what {@link #autowire} provides, adding {@link #initializeBean} behavior. 177 * @param beanClass the class of the bean to create 178 * @param autowireMode by name or type, using the constants in this interface 179 * @param dependencyCheck whether to perform a dependency check for objects 180 * (not applicable to autowiring a constructor, thus ignored there) 181 * @return the new bean instance 182 * @throws BeansException if instantiation or wiring failed 183 * @see #AUTOWIRE_NO 184 * @see #AUTOWIRE_BY_NAME 185 * @see #AUTOWIRE_BY_TYPE 186 * @see #AUTOWIRE_CONSTRUCTOR 187 */ 188 Object createBean(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; 189 190 /** 191 * Instantiate a new bean instance of the given class with the specified autowire 192 * strategy. All constants defined in this interface are supported here. 193 * Can also be invoked with {@code AUTOWIRE_NO} in order to just apply 194 * before-instantiation callbacks (e.g. for annotation-driven injection). 195 *

Does not apply standard {@link BeanPostProcessor BeanPostProcessors} 196 * callbacks or perform any further initialization of the bean. This interface 197 * offers distinct, fine-grained operations for those purposes, for example 198 * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor} 199 * callbacks are applied, if applicable to the construction of the instance. 200 * @param beanClass the class of the bean to instantiate 201 * @param autowireMode by name or type, using the constants in this interface 202 * @param dependencyCheck whether to perform a dependency check for object 203 * references in the bean instance (not applicable to autowiring a constructor, 204 * thus ignored there) 205 * @return the new bean instance 206 * @throws BeansException if instantiation or wiring failed 207 * @see #AUTOWIRE_NO 208 * @see #AUTOWIRE_BY_NAME 209 * @see #AUTOWIRE_BY_TYPE 210 * @see #AUTOWIRE_CONSTRUCTOR 211 * @see #AUTOWIRE_AUTODETECT 212 * @see #initializeBean 213 * @see #applyBeanPostProcessorsBeforeInitialization 214 * @see #applyBeanPostProcessorsAfterInitialization 215 */ 216 Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; 217 218 /** 219 * Autowire the bean properties of the given bean instance by name or type. 220 * Can also be invoked with {@code AUTOWIRE_NO} in order to just apply 221 * after-instantiation callbacks (e.g. for annotation-driven injection). 222 *

Does not apply standard {@link BeanPostProcessor BeanPostProcessors} 223 * callbacks or perform any further initialization of the bean. This interface 224 * offers distinct, fine-grained operations for those purposes, for example 225 * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor} 226 * callbacks are applied, if applicable to the configuration of the instance. 227 * @param existingBean the existing bean instance 228 * @param autowireMode by name or type, using the constants in this interface 229 * @param dependencyCheck whether to perform a dependency check for object 230 * references in the bean instance 231 * @throws BeansException if wiring failed 232 * @see #AUTOWIRE_BY_NAME 233 * @see #AUTOWIRE_BY_TYPE 234 * @see #AUTOWIRE_NO 235 */ 236 void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) 237 throws BeansException; 238 239 /** 240 * Apply the property values of the bean definition with the given name to 241 * the given bean instance. The bean definition can either define a fully 242 * self-contained bean, reusing its property values, or just property values 243 * meant to be used for existing bean instances. 244 *

This method does not autowire bean properties; it just applies 245 * explicitly defined property values. Use the {@link #autowireBeanProperties} 246 * method to autowire an existing bean instance. 247 * Note: This method requires a bean definition for the given name! 248 *

Does not apply standard {@link BeanPostProcessor BeanPostProcessors} 249 * callbacks or perform any further initialization of the bean. This interface 250 * offers distinct, fine-grained operations for those purposes, for example 251 * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor} 252 * callbacks are applied, if applicable to the configuration of the instance. 253 * @param existingBean the existing bean instance 254 * @param beanName the name of the bean definition in the bean factory 255 * (a bean definition of that name has to be available) 256 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException 257 * if there is no bean definition with the given name 258 * @throws BeansException if applying the property values failed 259 * @see #autowireBeanProperties 260 */ 261 void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException; 262 263 /** 264 * Initialize the given raw bean, applying factory callbacks 265 * such as {@code setBeanName} and {@code setBeanFactory}, 266 * also applying all bean post processors (including ones which 267 * might wrap the given raw bean). 268 *

Note that no bean definition of the given name has to exist 269 * in the bean factory. The passed-in bean name will simply be used 270 * for callbacks but not checked against the registered bean definitions. 271 * @param existingBean the existing bean instance 272 * @param beanName the name of the bean, to be passed to it if necessary 273 * (only passed to {@link BeanPostProcessor BeanPostProcessors}) 274 * @return the bean instance to use, either the original or a wrapped one 275 * @throws BeansException if the initialization failed 276 */ 277 Object initializeBean(Object existingBean, String beanName) throws BeansException; 278 279 /** 280 * Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean 281 * instance, invoking their {@code postProcessBeforeInitialization} methods. 282 * The returned bean instance may be a wrapper around the original. 283 * @param existingBean the new bean instance 284 * @param beanName the name of the bean 285 * @return the bean instance to use, either the original or a wrapped one 286 * @throws BeansException if any post-processing failed 287 * @see BeanPostProcessor#postProcessBeforeInitialization 288 */ 289 Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) 290 throws BeansException; 291 292 /** 293 * Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean 294 * instance, invoking their {@code postProcessAfterInitialization} methods. 295 * The returned bean instance may be a wrapper around the original. 296 * @param existingBean the new bean instance 297 * @param beanName the name of the bean 298 * @return the bean instance to use, either the original or a wrapped one 299 * @throws BeansException if any post-processing failed 300 * @see BeanPostProcessor#postProcessAfterInitialization 301 */ 302 Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) 303 throws BeansException; 304 305 /** 306 * Destroy the given bean instance (typically coming from {@link #createBean}), 307 * applying the {@link org.springframework.beans.factory.DisposableBean} contract as well as 308 * registered {@link DestructionAwareBeanPostProcessor DestructionAwareBeanPostProcessors}. 309 *

Any exception that arises during destruction should be caught 310 * and logged instead of propagated to the caller of this method. 311 * @param existingBean the bean instance to destroy 312 */ 313 void destroyBean(Object existingBean); 314 315 /** 316 * Resolve the specified dependency against the beans defined in this factory. 317 * @param descriptor the descriptor for the dependency 318 * @param beanName the name of the bean which declares the present dependency 319 * @param autowiredBeanNames a Set that all names of autowired beans (used for 320 * resolving the present dependency) are supposed to be added to 321 * @param typeConverter the TypeConverter to use for populating arrays and 322 * collections 323 * @return the resolved object, or {@code null} if none found 324 * @throws BeansException in dependency resolution failed 325 */ 326 Object resolveDependency(DependencyDescriptor descriptor, String beanName, 327 Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException; 328 329 }

View Code

这个接口我一直没用过..介绍里写可能用到的情况不多...

如果其他框架会产生一些不由Spring管理生命周期的bean的话可以通过这个接口取装配Bean.介绍里举了2个例子: WebWork Actions and Tapestry Page objects

 

小实验:接口里的方法我也没有仔细全部测,测了几个我觉得以后自己可能会用到的.因为我感觉用到这个接口的机会真的蛮小的.

 1     /**
 2      * AutowireCapableBeanFactory 测试
 3      */
 4     @Test
 5     public void testAutowireCapableBeanFactory() {
 6         AutowireCapableBeanFactory autowireCapableBeanFactory = this.applicationContext.getAutowireCapableBeanFactory();// DefaultListableBeanFactory
 7         BeanFactoryTest_Bean1 bean = new BeanFactoryTest_Bean1();
 8         autowireCapableBeanFactory.autowireBean(bean);
 9         System.out.println(bean); // BeanFactoryTest_Bean1{beanFactoryTest=spring.BeanFactoryTest@22088c28, myFactoryBean=spring.MyFactoryBean@5f29a78c, o=java.lang.Object@27b70923}
10 
11         System.out.println(autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean1.class)); // BeanFactoryTest_Bean1{beanFactoryTest=spring.BeanFactoryTest@22088c28, myFactoryBean=spring.MyFactoryBean@5f29a78c, o=java.lang.Object@33dce164}
12         System.out.println(autowireCapableBeanFactory.containsBean("beanFactoryTest_Bean1")); // false
13     }

 

1.如果自己new了1个对象,可以通过autowireCapableBeanFactory.autowireBean(bean);去装配这个对象.我在对象里是通过@Autowired去标注装配什么对象的.

因为对象是自己new的,所以不会做BeanPostProcessor里的postProcessBeforeInitialization方法和postProcessAfterInitialization方法

 

2.如果是autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean1.class)方法,除了装配以外还会做postProcessBeforeInitialization和postProcessAfterInitialization方法.

 

完整输出:

postProcessAfterInitialization=====myFactoryBean-1
BeanFactoryTest_Bean1{beanFactoryTest=spring.BeanFactoryTest@494f0b41, myFactoryBean=spring.MyFactoryBean@646bfe00, o=java.lang.Object@6df0e581}
postProcessAfterInitialization=====myFactoryBean-1
postProcessBeforeInitialization=====spring.BeanFactoryTest$BeanFactoryTest_Bean1
postProcessAfterInitialization=====spring.BeanFactoryTest$BeanFactoryTest_Bean1
BeanFactoryTest_Bean1{beanFactoryTest=spring.BeanFactoryTest@494f0b41, myFactoryBean=spring.MyFactoryBean@646bfe00, o=java.lang.Object@55a71fa6}
false

 

同时还有个小发现.myFactoryBean-1是一个由FactoryBean生成的对象,这些工厂对象生成的bean似乎不会做postProcessBeforeInitialization,只会做postProcessAfterInitialization.可能是因为你工厂没有做getObject之前Spring没有你的bean,所以不能postProcessBeforeInitialization的原因吧.      后来查了下资料.postProcessBeforeInitialization也是在new了以后设置了属性之后的....我觉得.可能是其他bean的afterProperties可能会扫描一些特性的bean做处理..这里工厂返回的bean肯定没有被之前扫描到.而postProcessBeforeInitialization是要在afterProperties之前做的(单个bean来说).所以这里不再执行.

ConfigurableBeanFactory

  1 /*
  2  * Copyright 2002-2012 the original author or authors.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package org.springframework.beans.factory.config;
 18 
 19 import java.beans.PropertyEditor;
 20 import java.security.AccessControlContext;
 21 
 22 import org.springframework.beans.PropertyEditorRegistrar;
 23 import org.springframework.beans.PropertyEditorRegistry;
 24 import org.springframework.beans.TypeConverter;
 25 import org.springframework.beans.factory.BeanDefinitionStoreException;
 26 import org.springframework.beans.factory.BeanFactory;
 27 import org.springframework.beans.factory.HierarchicalBeanFactory;
 28 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
 29 import org.springframework.core.convert.ConversionService;
 30 import org.springframework.util.StringValueResolver;
 31 
 32 /**
 33  * Configuration interface to be implemented by most bean factories. Provides
 34  * facilities to configure a bean factory, in addition to the bean factory
 35  * client methods in the {@link org.springframework.beans.factory.BeanFactory}
 36  * interface.
 37  *
 38  * 

This bean factory interface is not meant to be used in normal application 39 * code: Stick to {@link org.springframework.beans.factory.BeanFactory} or 40 * {@link org.springframework.beans.factory.ListableBeanFactory} for typical 41 * needs. This extended interface is just meant to allow for framework-internal 42 * plug'n'play and for special access to bean factory configuration methods. 43 * 44 * @author Juergen Hoeller 45 * @since 03.11.2003 46 * @see org.springframework.beans.factory.BeanFactory 47 * @see org.springframework.beans.factory.ListableBeanFactory 48 * @see ConfigurableListableBeanFactory 49 */ 50 public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry { 51 52 /** 53 * Scope identifier for the standard singleton scope: "singleton". 54 * Custom scopes can be added via {@code registerScope}. 55 * @see #registerScope 56 */ 57 String SCOPE_SINGLETON = "singleton"; 58 59 /** 60 * Scope identifier for the standard prototype scope: "prototype". 61 * Custom scopes can be added via {@code registerScope}. 62 * @see #registerScope 63 */ 64 String SCOPE_PROTOTYPE = "prototype"; 65 66 67 /** 68 * Set the parent of this bean factory. 69 *

Note that the parent cannot be changed: It should only be set outside 70 * a constructor if it isn't available at the time of factory instantiation. 71 * @param parentBeanFactory the parent BeanFactory 72 * @throws IllegalStateException if this factory is already associated with 73 * a parent BeanFactory 74 * @see #getParentBeanFactory() 75 */ 76 void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException; 77 78 /** 79 * Set the class loader to use for loading bean classes. 80 * Default is the thread context class loader. 81 *

Note that this class loader will only apply to bean definitions 82 * that do not carry a resolved bean class yet. This is the case as of 83 * Spring 2.0 by default: Bean definitions only carry bean class names, 84 * to be resolved once the factory processes the bean definition. 85 * @param beanClassLoader the class loader to use, 86 * or {@code null} to suggest the default class loader 87 */ 88 void setBeanClassLoader(ClassLoader beanClassLoader); 89 90 /** 91 * Return this factory's class loader for loading bean classes. 92 */ 93 ClassLoader getBeanClassLoader(); 94 95 /** 96 * Specify a temporary ClassLoader to use for type matching purposes. 97 * Default is none, simply using the standard bean ClassLoader. 98 *

A temporary ClassLoader is usually just specified if 99 * load-time weaving is involved, to make sure that actual bean 100 * classes are loaded as lazily as possible. The temporary loader is 101 * then removed once the BeanFactory completes its bootstrap phase. 102 * @since 2.5 103 */ 104 void setTempClassLoader(ClassLoader tempClassLoader); 105 106 /** 107 * Return the temporary ClassLoader to use for type matching purposes, 108 * if any. 109 * @since 2.5 110 */ 111 ClassLoader getTempClassLoader(); 112 113 /** 114 * Set whether to cache bean metadata such as given bean definitions 115 * (in merged fashion) and resolved bean classes. Default is on. 116 *

Turn this flag off to enable hot-refreshing of bean definition objects 117 * and in particular bean classes. If this flag is off, any creation of a bean 118 * instance will re-query the bean class loader for newly resolved classes. 119 */ 120 void setCacheBeanMetadata(boolean cacheBeanMetadata); 121 122 /** 123 * Return whether to cache bean metadata such as given bean definitions 124 * (in merged fashion) and resolved bean classes. 125 */ 126 boolean isCacheBeanMetadata(); 127 128 /** 129 * Specify the resolution strategy for expressions in bean definition values. 130 *

There is no expression support active in a BeanFactory by default. 131 * An ApplicationContext will typically set a standard expression strategy 132 * here, supporting "#{...}" expressions in a Unified EL compatible style. 133 * @since 3.0 134 */ 135 void setBeanExpressionResolver(BeanExpressionResolver resolver); 136 137 /** 138 * Return the resolution strategy for expressions in bean definition values. 139 * @since 3.0 140 */ 141 BeanExpressionResolver getBeanExpressionResolver(); 142 143 /** 144 * Specify a Spring 3.0 ConversionService to use for converting 145 * property values, as an alternative to JavaBeans PropertyEditors. 146 * @since 3.0 147 */ 148 void setConversionService(ConversionService conversionService); 149 150 /** 151 * Return the associated ConversionService, if any. 152 * @since 3.0 153 */ 154 ConversionService getConversionService(); 155 156 /** 157 * Add a PropertyEditorRegistrar to be applied to all bean creation processes. 158 *

Such a registrar creates new PropertyEditor instances and registers them 159 * on the given registry, fresh for each bean creation attempt. This avoids 160 * the need for synchronization on custom editors; hence, it is generally 161 * preferable to use this method instead of {@link #registerCustomEditor}. 162 * @param registrar the PropertyEditorRegistrar to register 163 */ 164 void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar); 165 166 /** 167 * Register the given custom property editor for all properties of the 168 * given type. To be invoked during factory configuration. 169 *

Note that this method will register a shared custom editor instance; 170 * access to that instance will be synchronized for thread-safety. It is 171 * generally preferable to use {@link #addPropertyEditorRegistrar} instead 172 * of this method, to avoid for the need for synchronization on custom editors. 173 * @param requiredType type of the property 174 * @param propertyEditorClass the {@link PropertyEditor} class to register 175 */ 176 void registerCustomEditor(Class requiredType, Classextends PropertyEditor> propertyEditorClass); 177 178 /** 179 * Initialize the given PropertyEditorRegistry with the custom editors 180 * that have been registered with this BeanFactory. 181 * @param registry the PropertyEditorRegistry to initialize 182 */ 183 void copyRegisteredEditorsTo(PropertyEditorRegistry registry); 184 185 /** 186 * Set a custom type converter that this BeanFactory should use for converting 187 * bean property values, constructor argument values, etc. 188 *

This will override the default PropertyEditor mechanism and hence make 189 * any custom editors or custom editor registrars irrelevant. 190 * @see #addPropertyEditorRegistrar 191 * @see #registerCustomEditor 192 * @since 2.5 193 */ 194 void setTypeConverter(TypeConverter typeConverter); 195 196 /** 197 * Obtain a type converter as used by this BeanFactory. This may be a fresh 198 * instance for each call, since TypeConverters are usually not thread-safe. 199 *

If the default PropertyEditor mechanism is active, the returned 200 * TypeConverter will be aware of all custom editors that have been registered. 201 * @since 2.5 202 */ 203 TypeConverter getTypeConverter(); 204 205 /** 206 * Add a String resolver for embedded values such as annotation attributes. 207 * @param valueResolver the String resolver to apply to embedded values 208 * @since 3.0 209 */ 210 void addEmbeddedValueResolver(StringValueResolver valueResolver); 211 212 /** 213 * Resolve the given embedded value, e.g. an annotation attribute. 214 * @param value the value to resolve 215 * @return the resolved value (may be the original value as-is) 216 * @since 3.0 217 */ 218 String resolveEmbeddedValue(String value); 219 220 /** 221 * Add a new BeanPostProcessor that will get applied to beans created 222 * by this factory. To be invoked during factory configuration. 223 *

Note: Post-processors submitted here will be applied in the order of 224 * registration; any ordering semantics expressed through implementing the 225 * {@link org.springframework.core.Ordered} interface will be ignored. Note 226 * that autodetected post-processors (e.g. as beans in an ApplicationContext) 227 * will always be applied after programmatically registered ones. 228 * @param beanPostProcessor the post-processor to register 229 */ 230 void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); 231 232 /** 233 * Return the current number of registered BeanPostProcessors, if any. 234 */ 235 int getBeanPostProcessorCount(); 236 237 /** 238 * Register the given scope, backed by the given Scope implementation. 239 * @param scopeName the scope identifier 240 * @param scope the backing Scope implementation 241 */ 242 void registerScope(String scopeName, Scope scope); 243 244 /** 245 * Return the names of all currently registered scopes. 246 *

This will only return the names of explicitly registered scopes. 247 * Built-in scopes such as "singleton" and "prototype" won't be exposed. 248 * @return the array of scope names, or an empty array if none 249 * @see #registerScope 250 */ 251 String[] getRegisteredScopeNames(); 252 253 /** 254 * Return the Scope implementation for the given scope name, if any. 255 *

This will only return explicitly registered scopes. 256 * Built-in scopes such as "singleton" and "prototype" won't be exposed. 257 * @param scopeName the name of the scope 258 * @return the registered Scope implementation, or {@code null} if none 259 * @see #registerScope 260 */ 261 Scope getRegisteredScope(String scopeName); 262 263 /** 264 * Provides a security access control context relevant to this factory. 265 * @return the applicable AccessControlContext (never {@code null}) 266 * @since 3.0 267 */ 268 AccessControlContext getAccessControlContext(); 269 270 /** 271 * Copy all relevant configuration from the given other factory. 272 *

Should include all standard configuration settings as well as 273 * BeanPostProcessors, Scopes, and factory-specific internal settings. 274 * Should not include any metadata of actual bean definitions, 275 * such as BeanDefinition objects and bean name aliases. 276 * @param otherFactory the other BeanFactory to copy from 277 */ 278 void copyConfigurationFrom(ConfigurableBeanFactory otherFactory); 279 280 /** 281 * Given a bean name, create an alias. We typically use this method to 282 * support names that are illegal within XML ids (used for bean names). 283 *

Typically invoked during factory configuration, but can also be 284 * used for runtime registration of aliases. Therefore, a factory 285 * implementation should synchronize alias access. 286 * @param beanName the canonical name of the target bean 287 * @param alias the alias to be registered for the bean 288 * @throws BeanDefinitionStoreException if the alias is already in use 289 */ 290 void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; 291 292 /** 293 * Resolve all alias target names and aliases registered in this 294 * factory, applying the given StringValueResolver to them. 295 *

The value resolver may for example resolve placeholders 296 * in target bean names and even in alias names. 297 * @param valueResolver the StringValueResolver to apply 298 * @since 2.5 299 */ 300 void resolveAliases(StringValueResolver valueResolver); 301 302 /** 303 * Return a merged BeanDefinition for the given bean name, 304 * merging a child bean definition with its parent if necessary. 305 * Considers bean definitions in ancestor factories as well. 306 * @param beanName the name of the bean to retrieve the merged definition for 307 * @return a (potentially merged) BeanDefinition for the given bean 308 * @throws NoSuchBeanDefinitionException if there is no bean definition with the given name 309 * @since 2.5 310 */ 311 BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; 312 313 /** 314 * Determine whether the bean with the given name is a FactoryBean. 315 * @param name the name of the bean to check 316 * @return whether the bean is a FactoryBean 317 * ({@code false} means the bean exists but is not a FactoryBean) 318 * @throws NoSuchBeanDefinitionException if there is no bean with the given name 319 * @since 2.5 320 */ 321 boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException; 322 323 /** 324 * Explicitly control the current in-creation status of the specified bean. 325 * For container-internal use only. 326 * @param beanName the name of the bean 327 * @param inCreation whether the bean is currently in creation 328 * @since 3.1 329 */ 330 void setCurrentlyInCreation(String beanName, boolean inCreation); 331 332 /** 333 * Determine whether the specified bean is currently in creation. 334 * @param beanName the name of the bean 335 * @return whether the bean is currently in creation 336 * @since 2.5 337 */ 338 boolean isCurrentlyInCreation(String beanName); 339 340 /** 341 * Register a dependent bean for the given bean, 342 * to be destroyed before the given bean is destroyed. 343 * @param beanName the name of the bean 344 * @param dependentBeanName the name of the dependent bean 345 * @since 2.5 346 */ 347 void registerDependentBean(String beanName, String dependentBeanName); 348 349 /** 350 * Return the names of all beans which depend on the specified bean, if any. 351 * @param beanName the name of the bean 352 * @return the array of dependent bean names, or an empty array if none 353 * @since 2.5 354 */ 355 String[] getDependentBeans(String beanName); 356 357 /** 358 * Return the names of all beans that the specified bean depends on, if any. 359 * @param beanName the name of the bean 360 * @return the array of names of beans which the bean depends on, 361 * or an empty array if none 362 * @since 2.5 363 */ 364 String[] getDependenciesForBean(String beanName); 365 366 /** 367 * Destroy the given bean instance (usually a prototype instance 368 * obtained from this factory) according to its bean definition. 369 *

Any exception that arises during destruction should be caught 370 * and logged instead of propagated to the caller of this method. 371 * @param beanName the name of the bean definition 372 * @param beanInstance the bean instance to destroy 373 */ 374 void destroyBean(String beanName, Object beanInstance); 375 376 /** 377 * Destroy the specified scoped bean in the current target scope, if any. 378 *

Any exception that arises during destruction should be caught 379 * and logged instead of propagated to the caller of this method. 380 * @param beanName the name of the scoped bean 381 */ 382 void destroyScopedBean(String beanName); 383 384 /** 385 * Destroy all singleton beans in this factory, including inner beans that have 386 * been registered as disposable. To be called on shutdown of a factory. 387 *

Any exception that arises during destruction should be caught 388 * and logged instead of propagated to the caller of this method. 389 */ 390 void destroySingletons(); 391 392 }

View Code

 可以配置的工厂,一般可能也不会用到..而且我想一般人可能不会去修改啥配置吧..

比如我们bean的属性可以用@Value注入,我们可以再这里进行SPEL表达式的一些配置

 1     /**
 2      * 测试 ConfigurableBeanFactory
 3      */
 4     @Test
 5     public void testConfigurableBeanFactory() {
 6         DefaultListableBeanFactory autowireCapableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
 7 
 8         BeanFactoryTest_Bean2 bean1 = autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean2.class);
 9         System.out.println(bean1); // BeanFactoryTest_Bean2{value='spring.BeanFactoryTest@1ca14537'}
10 
11         //EL有缓存所以要信create1个bean
12         StandardBeanExpressionResolver beanExpressionResolver = (StandardBeanExpressionResolver) autowireCapableBeanFactory.getBeanExpressionResolver();
13         beanExpressionResolver.setExpressionPrefix("#(");
14         beanExpressionResolver.setExpressionSuffix(")");
15         BeanFactoryTest_Bean3 bean3 = autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean3.class);
16         System.out.println(bean3); // BeanFactoryTest_Bean3{value='spring.BeanFactoryTest@1ca14537'}
17     }
18 
19     private static class BeanFactoryTest_Bean2 {
20         @Value("#{@myBeanFactoryTestBean.toString()}")
21         public String value;
22 
23         @Override
24         public String toString() {
25             return "BeanFactoryTest_Bean2{" +
26                     "value='" + value + '\'' +
27                     '}';
28         }
29     }
30 
31     private static class BeanFactoryTest_Bean3 {
32 
33         @Value("#(@myBeanFactoryTestBean.toString())")
34         public String value;
35 
36         @Override
37         public String toString() {
38             return "BeanFactoryTest_Bean3{" +
39                     "value='" + value + '\'' +
40                     '}';
41         }
42     }

写了2个bean去做测试是因为EL表达式有缓存..解析过以后结果会被缓存..所以写了2个bean去做测试.

自己配置了个表达式的前缀是#(后缀是),默认是#{和}....一般我想没人会去修改吧....

 

还有就是这个接口提供了getConversionService的方法.不过我实际测试返回的是null...不知道是不是因为我是在junit里测试的原因..这样的话就不用通过Environment去获取了..不过也没差多少.

 

另外还可以设置BeanPostProcessor.

 1         System.out.println(autowireCapableBeanFactory.getBeanPostProcessorCount()); // 11
 2         autowireCapableBeanFactory.addBeanPostProcessor(new BeanPostProcessor() {
 3             @Override
 4             public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
 5                 System.out.println("MyBeanPostProcessor -> postProcessBeforeInitialization");
 6                 return bean;
 7             }
 8 
 9             @Override
10             public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
11                 System.out.println("MyBeanPostProcessor -> postProcessAfterInitialization");
12                 return bean;
13             }
14         });
15         System.out.println(autowireCapableBeanFactory.getBeanPostProcessorCount()); // 12
16         // MyBeanPostProcessor -> postProcessBeforeInitialization
17         // MyBeanPostProcessor -> postProcessAfterInitialization
18         BeanFactoryTest_Bean3 bean4 = autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean3.class);

 

ConfigurableListableBeanFactory

  1 /*
  2  * Copyright 2002-2014 the original author or authors.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package org.springframework.beans.factory.config;
 18 
 19 import java.util.Iterator;
 20 
 21 import org.springframework.beans.BeansException;
 22 import org.springframework.beans.factory.ListableBeanFactory;
 23 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
 24 
 25 /**
 26  * Configuration interface to be implemented by most listable bean factories.
 27  * In addition to {@link ConfigurableBeanFactory}, it provides facilities to
 28  * analyze and modify bean definitions, and to pre-instantiate singletons.
 29  *
 30  * 

This subinterface of {@link org.springframework.beans.factory.BeanFactory} 31 * is not meant to be used in normal application code: Stick to 32 * {@link org.springframework.beans.factory.BeanFactory} or 33 * {@link org.springframework.beans.factory.ListableBeanFactory} for typical 34 * use cases. This interface is just meant to allow for framework-internal 35 * plug'n'play even when needing access to bean factory configuration methods. 36 * 37 * @author Juergen Hoeller 38 * @since 03.11.2003 39 * @see org.springframework.context.support.AbstractApplicationContext#getBeanFactory() 40 */ 41 public interface ConfigurableListableBeanFactory 42 extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory { 43 44 /** 45 * Ignore the given dependency type for autowiring: 46 * for example, String. Default is none. 47 * @param type the dependency type to ignore 48 */ 49 void ignoreDependencyType(Class type); 50 51 /** 52 * Ignore the given dependency interface for autowiring. 53 *

This will typically be used by application contexts to register 54 * dependencies that are resolved in other ways, like BeanFactory through 55 * BeanFactoryAware or ApplicationContext through ApplicationContextAware. 56 *

By default, only the BeanFactoryAware interface is ignored. 57 * For further types to ignore, invoke this method for each type. 58 * @param ifc the dependency interface to ignore 59 * @see org.springframework.beans.factory.BeanFactoryAware 60 * @see org.springframework.context.ApplicationContextAware 61 */ 62 void ignoreDependencyInterface(Class ifc); 63 64 /** 65 * Register a special dependency type with corresponding autowired value. 66 *

This is intended for factory/context references that are supposed 67 * to be autowirable but are not defined as beans in the factory: 68 * e.g. a dependency of type ApplicationContext resolved to the 69 * ApplicationContext instance that the bean is living in. 70 *

Note: There are no such default types registered in a plain BeanFactory, 71 * not even for the BeanFactory interface itself. 72 * @param dependencyType the dependency type to register. This will typically 73 * be a base interface such as BeanFactory, with extensions of it resolved 74 * as well if declared as an autowiring dependency (e.g. ListableBeanFactory), 75 * as long as the given value actually implements the extended interface. 76 * @param autowiredValue the corresponding autowired value. This may also be an 77 * implementation of the {@link org.springframework.beans.factory.ObjectFactory} 78 * interface, which allows for lazy resolution of the actual target value. 79 */ 80 void registerResolvableDependency(Class dependencyType, Object autowiredValue); 81 82 /** 83 * Determine whether the specified bean qualifies as an autowire candidate, 84 * to be injected into other beans which declare a dependency of matching type. 85 *

This method checks ancestor factories as well. 86 * @param beanName the name of the bean to check 87 * @param descriptor the descriptor of the dependency to resolve 88 * @return whether the bean should be considered as autowire candidate 89 * @throws NoSuchBeanDefinitionException if there is no bean with the given name 90 */ 91 boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) 92 throws NoSuchBeanDefinitionException; 93 94 /** 95 * Return the registered BeanDefinition for the specified bean, allowing access 96 * to its property values and constructor argument value (which can be 97 * modified during bean factory post-processing). 98 *

A returned BeanDefinition object should not be a copy but the original 99 * definition object as registered in the factory. This means that it should 100 * be castable to a more specific implementation type, if necessary. 101 *

NOTE: This method does not consider ancestor factories. 102 * It is only meant for accessing local bean definitions of this factory. 103 * @param beanName the name of the bean 104 * @return the registered BeanDefinition 105 * @throws NoSuchBeanDefinitionException if there is no bean with the given name 106 * defined in this factory 107 */ 108 BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; 109 110 /** 111 * Return a unified view over all bean names managed by this factory. 112 *

Includes bean definition names as well as names of manually registered 113 * singleton instances, with bean definition names consistently coming first, 114 * analogous to how type/annotation specific retrieval of bean names works. 115 * @return the composite iterator for the bean names view 116 * @since 4.1.2 117 * @see #containsBeanDefinition 118 * @see #registerSingleton 119 * @see #getBeanNamesForType 120 * @see #getBeanNamesForAnnotation 121 */ 122 Iterator getBeanNamesIterator(); 123 124 /** 125 * Freeze all bean definitions, signalling that the registered bean definitions 126 * will not be modified or post-processed any further. 127 *

This allows the factory to aggressively cache bean definition metadata. 128 */ 129 void freezeConfiguration(); 130 131 /** 132 * Return whether this factory's bean definitions are frozen, 133 * i.e. are not supposed to be modified or post-processed any further. 134 * @return {@code true} if the factory's configuration is considered frozen 135 */ 136 boolean isConfigurationFrozen(); 137 138 /** 139 * Ensure that all non-lazy-init singletons are instantiated, also considering 140 * {@link org.springframework.beans.factory.FactoryBean FactoryBeans}. 141 * Typically invoked at the end of factory setup, if desired. 142 * @throws BeansException if one of the singleton beans could not be created. 143 * Note: This may have left the factory with some beans already initialized! 144 * Call {@link #destroySingletons()} for full cleanup in this case. 145 * @see #destroySingletons() 146 */ 147 void preInstantiateSingletons() throws BeansException; 148 149 }

View Code

 

这个接口根据文档上写的.似乎也不是给外部使用的,相比较ConfigurableBeanFactory,还提供了bean definitions和pre-instantiate的能力

没有使用过,不懂具体哪些地方会用到.用到的时候再补充吧.

 

以上便是我对BeanFactory接口的简单认识

 

你可能感兴趣的:(Spring 学习记录5 BeanFactory)