主题

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

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

结构

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

小实验:

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

HierarchicalBeanFactory

 /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.beans.factory; /**
* Sub-interface implemented by bean factories that can be part
* of a hierarchy.
*
* <p>The corresponding {@code setParentBeanFactory} method for bean
* factories that allow setting the parent in a configurable
* fashion can be found in the ConfigurableBeanFactory interface.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 07.07.2003
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setParentBeanFactory
*/
public interface HierarchicalBeanFactory extends BeanFactory { /**
* Return the parent bean factory, or {@code null} if there is none.
*/
BeanFactory getParentBeanFactory(); /**
* Return whether the local bean factory contains a bean of the given name,
* ignoring beans defined in ancestor contexts.
* <p>This is an alternative to {@code containsBean}, ignoring a bean
* of the given name from an ancestor bean factory.
* @param name the name of the bean to query
* @return whether a bean with the given name is defined in the local factory
* @see BeanFactory#containsBean
*/
boolean containsLocalBean(String name); }

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

getParentBeanFactory方法可以获取父级BeanFactory

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

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

ListableBeanFactory

 /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.beans.factory; import java.lang.annotation.Annotation;
import java.util.Map; import org.springframework.beans.BeansException; /**
* Extension of the {@link BeanFactory} interface to be implemented by bean factories
* that can enumerate all their bean instances, rather than attempting bean lookup
* by name one by one as requested by clients. BeanFactory implementations that
* preload all their bean definitions (such as XML-based factories) may implement
* this interface.
*
* <p>If this is a {@link HierarchicalBeanFactory}, the return values will <i>not</i>
* take any BeanFactory hierarchy into account, but will relate only to the beans
* defined in the current factory. Use the {@link BeanFactoryUtils} helper class
* to consider beans in ancestor factories too.
*
* <p>The methods in this interface will just respect bean definitions of this factory.
* They will ignore any singleton beans that have been registered by other means like
* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}'s
* {@code registerSingleton} method, with the exception of
* {@code getBeanNamesOfType} and {@code getBeansOfType} which will check
* such manually registered singletons too. Of course, BeanFactory's {@code getBean}
* does allow transparent access to such special beans as well. However, in typical
* scenarios, all beans will be defined by external bean definitions anyway, so most
* applications don't need to worry about this differentiation.
*
* <p><b>NOTE:</b> With the exception of {@code getBeanDefinitionCount}
* and {@code containsBeanDefinition}, the methods in this interface
* are not designed for frequent invocation. Implementations may be slow.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 16 April 2001
* @see HierarchicalBeanFactory
* @see BeanFactoryUtils
*/
public interface ListableBeanFactory extends BeanFactory { /**
* Check if this bean factory contains a bean definition with the given name.
* <p>Does not consider any hierarchy this factory may participate in,
* and ignores any singleton beans that have been registered by
* other means than bean definitions.
* @param beanName the name of the bean to look for
* @return if this bean factory contains a bean definition with the given name
* @see #containsBean
*/
boolean containsBeanDefinition(String beanName); /**
* Return the number of beans defined in the factory.
* <p>Does not consider any hierarchy this factory may participate in,
* and ignores any singleton beans that have been registered by
* other means than bean definitions.
* @return the number of beans defined in the factory
*/
int getBeanDefinitionCount(); /**
* Return the names of all beans defined in this factory.
* <p>Does not consider any hierarchy this factory may participate in,
* and ignores any singleton beans that have been registered by
* other means than bean definitions.
* @return the names of all beans defined in this factory,
* or an empty array if none defined
*/
String[] getBeanDefinitionNames(); /**
* Return the names of beans matching the given type (including subclasses),
* judging from either bean definitions or the value of {@code getObjectType}
* in the case of FactoryBeans.
* <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
* check nested beans which might match the specified type as well.
* <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
* will get initialized. If the object created by the FactoryBean doesn't match,
* the raw FactoryBean itself will be matched against the type.
* <p>Does not consider any hierarchy this factory may participate in.
* Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
* to include beans in ancestor factories too.
* <p>Note: Does <i>not</i> ignore singleton beans that have been registered
* by other means than bean definitions.
* <p>This version of {@code getBeanNamesForType} matches all kinds of beans,
* be it singletons, prototypes, or FactoryBeans. In most implementations, the
* result will be the same as for {@code getBeanNamesForType(type, true, true)}.
* <p>Bean names returned by this method should always return bean names <i>in the
* order of definition</i> in the backend configuration, as far as possible.
* @param type the class or interface to match, or {@code null} for all bean names
* @return the names of beans (or objects created by FactoryBeans) matching
* the given object type (including subclasses), or an empty array if none
* @see FactoryBean#getObjectType
* @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class)
*/
String[] getBeanNamesForType(Class<?> type); /**
* Return the names of beans matching the given type (including subclasses),
* judging from either bean definitions or the value of {@code getObjectType}
* in the case of FactoryBeans.
* <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
* check nested beans which might match the specified type as well.
* <p>Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set,
* which means that FactoryBeans will get initialized. If the object created by the
* FactoryBean doesn't match, the raw FactoryBean itself will be matched against the
* type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
* (which doesn't require initialization of each FactoryBean).
* <p>Does not consider any hierarchy this factory may participate in.
* Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
* to include beans in ancestor factories too.
* <p>Note: Does <i>not</i> ignore singleton beans that have been registered
* by other means than bean definitions.
* <p>Bean names returned by this method should always return bean names <i>in the
* order of definition</i> in the backend configuration, as far as possible.
* @param type the class or interface to match, or {@code null} for all bean names
* @param includeNonSingletons whether to include prototype or scoped beans too
* or just singletons (also applies to FactoryBeans)
* @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
* <i>objects created by FactoryBeans</i> (or by factory methods with a
* "factory-bean" reference) for the type check. Note that FactoryBeans need to be
* eagerly initialized to determine their type: So be aware that passing in "true"
* for this flag will initialize FactoryBeans and "factory-bean" references.
* @return the names of beans (or objects created by FactoryBeans) matching
* the given object type (including subclasses), or an empty array if none
* @see FactoryBean#getObjectType
* @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
*/
String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit); /**
* Return the bean instances that match the given object type (including
* subclasses), judging from either bean definitions or the value of
* {@code getObjectType} in the case of FactoryBeans.
* <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
* check nested beans which might match the specified type as well.
* <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
* will get initialized. If the object created by the FactoryBean doesn't match,
* the raw FactoryBean itself will be matched against the type.
* <p>Does not consider any hierarchy this factory may participate in.
* Use BeanFactoryUtils' {@code beansOfTypeIncludingAncestors}
* to include beans in ancestor factories too.
* <p>Note: Does <i>not</i> ignore singleton beans that have been registered
* by other means than bean definitions.
* <p>This version of getBeansOfType matches all kinds of beans, be it
* singletons, prototypes, or FactoryBeans. In most implementations, the
* result will be the same as for {@code getBeansOfType(type, true, true)}.
* <p>The Map returned by this method should always return bean names and
* corresponding bean instances <i>in the order of definition</i> in the
* backend configuration, as far as possible.
* @param type the class or interface to match, or {@code null} for all concrete beans
* @return a Map with the matching beans, containing the bean names as
* keys and the corresponding bean instances as values
* @throws BeansException if a bean could not be created
* @since 1.1.2
* @see FactoryBean#getObjectType
* @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
*/
<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException; /**
* Return the bean instances that match the given object type (including
* subclasses), judging from either bean definitions or the value of
* {@code getObjectType} in the case of FactoryBeans.
* <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
* check nested beans which might match the specified type as well.
* <p>Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set,
* which means that FactoryBeans will get initialized. If the object created by the
* FactoryBean doesn't match, the raw FactoryBean itself will be matched against the
* type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
* (which doesn't require initialization of each FactoryBean).
* <p>Does not consider any hierarchy this factory may participate in.
* Use BeanFactoryUtils' {@code beansOfTypeIncludingAncestors}
* to include beans in ancestor factories too.
* <p>Note: Does <i>not</i> ignore singleton beans that have been registered
* by other means than bean definitions.
* <p>The Map returned by this method should always return bean names and
* corresponding bean instances <i>in the order of definition</i> in the
* backend configuration, as far as possible.
* @param type the class or interface to match, or {@code null} for all concrete beans
* @param includeNonSingletons whether to include prototype or scoped beans too
* or just singletons (also applies to FactoryBeans)
* @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
* <i>objects created by FactoryBeans</i> (or by factory methods with a
* "factory-bean" reference) for the type check. Note that FactoryBeans need to be
* eagerly initialized to determine their type: So be aware that passing in "true"
* for this flag will initialize FactoryBeans and "factory-bean" references.
* @return a Map with the matching beans, containing the bean names as
* keys and the corresponding bean instances as values
* @throws BeansException if a bean could not be created
* @see FactoryBean#getObjectType
* @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
*/
<T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException; /**
* Find all names of beans whose {@code Class} has the supplied {@link Annotation}
* type, without creating any bean instances yet.
* @param annotationType the type of annotation to look for
* @return the names of all matching beans
* @since 4.0
*/
String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType); /**
* Find all beans whose {@code Class} has the supplied {@link Annotation} type,
* returning a Map of bean names with corresponding bean instances.
* @param annotationType the type of annotation to look for
* @return a Map with the matching beans, containing the bean names as
* keys and the corresponding bean instances as values
* @throws BeansException if a bean could not be created
* @since 3.0
*/
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException; /**
* Find an {@link Annotation} of {@code annotationType} on the specified
* bean, traversing its interfaces and super classes if no annotation can be
* found on the given class itself.
* @param beanName the name of the bean to look for annotations on
* @param annotationType the annotation class to look for
* @return the annotation of the given type if found, or {@code null}
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 3.0
*/
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException; }

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

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

<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;

Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

这2个方法..

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

小实验:

     /**
* ListableBeanFactory HierarchicalBeanFactory 测试
*/
@Test
public void testListableBeanFactoryAndHierarchicalBeanFactory() {
// ListableBeanFactory里的方法不会考虑parent里的bean
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) this.applicationContext.getAutowireCapableBeanFactory(); // DefaultListableBeanFactory
DefaultListableBeanFactory child = new DefaultListableBeanFactory();
child.setParentBeanFactory(beanFactory); // 设置 System.out.println(child.getBeansOfType(BeanFactoryTest.class)); // {}
System.out.println(child.containsLocalBean("myBeanFactoryTestBean")); // false
System.out.println(child.containsBean("myBeanFactoryTestBean")); // true
System.out.println(BeanFactoryUtils.beansOfTypeIncludingAncestors(child, BeanFactoryTest.class)); // {myBeanFactoryTestBean=spring.BeanFactoryTest@3616a983} System.out.println(child.getBeansWithAnnotation(RunWith.class)); // {}
System.out.println(beanFactory.getBeansWithAnnotation(RunWith.class)); // {myBeanFactoryTestBean=spring.BeanFactoryTest@3616a983}
}

AutowireCapableBeanFactory

 /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.beans.factory.config; import java.util.Set; import org.springframework.beans.BeansException;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.BeanFactory; /**
* Extension of the {@link org.springframework.beans.factory.BeanFactory}
* interface to be implemented by bean factories that are capable of
* autowiring, provided that they want to expose this functionality for
* existing bean instances.
*
* <p>This subinterface of BeanFactory is not meant to be used in normal
* application code: stick to {@link org.springframework.beans.factory.BeanFactory}
* or {@link org.springframework.beans.factory.ListableBeanFactory} for
* typical use cases.
*
* <p>Integration code for other frameworks can leverage this interface to
* wire and populate existing bean instances that Spring does not control
* the lifecycle of. This is particularly useful for WebWork Actions and
* Tapestry Page objects, for example.
*
* <p>Note that this interface is not implemented by
* {@link org.springframework.context.ApplicationContext} facades,
* as it is hardly ever used by application code. That said, it is available
* from an application context too, accessible through ApplicationContext's
* {@link org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()}
* method.
*
* <p>You may also implement the {@link org.springframework.beans.factory.BeanFactoryAware}
* interface, which exposes the internal BeanFactory even when running in an
* ApplicationContext, to get access to an AutowireCapableBeanFactory:
* simply cast the passed-in BeanFactory to AutowireCapableBeanFactory.
*
* @author Juergen Hoeller
* @since 04.12.2003
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory
* @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
*/
public interface AutowireCapableBeanFactory extends BeanFactory { /**
* Constant that indicates no externally defined autowiring. Note that
* BeanFactoryAware etc and annotation-driven injection will still be applied.
* @see #createBean
* @see #autowire
* @see #autowireBeanProperties
*/
int AUTOWIRE_NO = 0; /**
* Constant that indicates autowiring bean properties by name
* (applying to all bean property setters).
* @see #createBean
* @see #autowire
* @see #autowireBeanProperties
*/
int AUTOWIRE_BY_NAME = 1; /**
* Constant that indicates autowiring bean properties by type
* (applying to all bean property setters).
* @see #createBean
* @see #autowire
* @see #autowireBeanProperties
*/
int AUTOWIRE_BY_TYPE = 2; /**
* Constant that indicates autowiring the greediest constructor that
* can be satisfied (involves resolving the appropriate constructor).
* @see #createBean
* @see #autowire
*/
int AUTOWIRE_CONSTRUCTOR = 3; /**
* Constant that indicates determining an appropriate autowire strategy
* through introspection of the bean class.
* @see #createBean
* @see #autowire
* @deprecated as of Spring 3.0: If you are using mixed autowiring strategies,
* prefer annotation-based autowiring for clearer demarcation of autowiring needs.
*/
@Deprecated
int AUTOWIRE_AUTODETECT = 4; //-------------------------------------------------------------------------
// Typical methods for creating and populating external bean instances
//------------------------------------------------------------------------- /**
* Fully create a new bean instance of the given class.
* <p>Performs full initialization of the bean, including all applicable
* {@link BeanPostProcessor BeanPostProcessors}.
* <p>Note: This is intended for creating a fresh instance, populating annotated
* fields and methods as well as applying all standard bean initialiation callbacks.
* It does <i>not</> imply traditional by-name or by-type autowiring of properties;
* use {@link #createBean(Class, int, boolean)} for that purposes.
* @param beanClass the class of the bean to create
* @return the new bean instance
* @throws BeansException if instantiation or wiring failed
*/
<T> T createBean(Class<T> beanClass) throws BeansException; /**
* Populate the given bean instance through applying after-instantiation callbacks
* and bean property post-processing (e.g. for annotation-driven injection).
* <p>Note: This is essentially intended for (re-)populating annotated fields and
* methods, either for new instances or for deserialized instances. It does
* <i>not</i> imply traditional by-name or by-type autowiring of properties;
* use {@link #autowireBeanProperties} for that purposes.
* @param existingBean the existing bean instance
* @throws BeansException if wiring failed
*/
void autowireBean(Object existingBean) throws BeansException; /**
* Configure the given raw bean: autowiring bean properties, applying
* bean property values, applying factory callbacks such as {@code setBeanName}
* and {@code setBeanFactory}, and also applying all bean post processors
* (including ones which might wrap the given raw bean).
* <p>This is effectively a superset of what {@link #initializeBean} provides,
* fully applying the configuration specified by the corresponding bean definition.
* <b>Note: This method requires a bean definition for the given name!</b>
* @param existingBean the existing bean instance
* @param beanName the name of the bean, to be passed to it if necessary
* (a bean definition of that name has to be available)
* @return the bean instance to use, either the original or a wrapped one
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
* if there is no bean definition with the given name
* @throws BeansException if the initialization failed
* @see #initializeBean
*/
Object configureBean(Object existingBean, String beanName) throws BeansException; /**
* Resolve the specified dependency against the beans defined in this factory.
* @param descriptor the descriptor for the dependency
* @param beanName the name of the bean which declares the present dependency
* @return the resolved object, or {@code null} if none found
* @throws BeansException in dependency resolution failed
*/
Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException; //-------------------------------------------------------------------------
// Specialized methods for fine-grained control over the bean lifecycle
//------------------------------------------------------------------------- /**
* Fully create a new bean instance of the given class with the specified
* autowire strategy. All constants defined in this interface are supported here.
* <p>Performs full initialization of the bean, including all applicable
* {@link BeanPostProcessor BeanPostProcessors}. This is effectively a superset
* of what {@link #autowire} provides, adding {@link #initializeBean} behavior.
* @param beanClass the class of the bean to create
* @param autowireMode by name or type, using the constants in this interface
* @param dependencyCheck whether to perform a dependency check for objects
* (not applicable to autowiring a constructor, thus ignored there)
* @return the new bean instance
* @throws BeansException if instantiation or wiring failed
* @see #AUTOWIRE_NO
* @see #AUTOWIRE_BY_NAME
* @see #AUTOWIRE_BY_TYPE
* @see #AUTOWIRE_CONSTRUCTOR
*/
Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; /**
* Instantiate a new bean instance of the given class with the specified autowire
* strategy. All constants defined in this interface are supported here.
* Can also be invoked with {@code AUTOWIRE_NO} in order to just apply
* before-instantiation callbacks (e.g. for annotation-driven injection).
* <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
* callbacks or perform any further initialization of the bean. This interface
* offers distinct, fine-grained operations for those purposes, for example
* {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
* callbacks are applied, if applicable to the construction of the instance.
* @param beanClass the class of the bean to instantiate
* @param autowireMode by name or type, using the constants in this interface
* @param dependencyCheck whether to perform a dependency check for object
* references in the bean instance (not applicable to autowiring a constructor,
* thus ignored there)
* @return the new bean instance
* @throws BeansException if instantiation or wiring failed
* @see #AUTOWIRE_NO
* @see #AUTOWIRE_BY_NAME
* @see #AUTOWIRE_BY_TYPE
* @see #AUTOWIRE_CONSTRUCTOR
* @see #AUTOWIRE_AUTODETECT
* @see #initializeBean
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #applyBeanPostProcessorsAfterInitialization
*/
Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; /**
* Autowire the bean properties of the given bean instance by name or type.
* Can also be invoked with {@code AUTOWIRE_NO} in order to just apply
* after-instantiation callbacks (e.g. for annotation-driven injection).
* <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
* callbacks or perform any further initialization of the bean. This interface
* offers distinct, fine-grained operations for those purposes, for example
* {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
* callbacks are applied, if applicable to the configuration of the instance.
* @param existingBean the existing bean instance
* @param autowireMode by name or type, using the constants in this interface
* @param dependencyCheck whether to perform a dependency check for object
* references in the bean instance
* @throws BeansException if wiring failed
* @see #AUTOWIRE_BY_NAME
* @see #AUTOWIRE_BY_TYPE
* @see #AUTOWIRE_NO
*/
void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
throws BeansException; /**
* Apply the property values of the bean definition with the given name to
* the given bean instance. The bean definition can either define a fully
* self-contained bean, reusing its property values, or just property values
* meant to be used for existing bean instances.
* <p>This method does <i>not</i> autowire bean properties; it just applies
* explicitly defined property values. Use the {@link #autowireBeanProperties}
* method to autowire an existing bean instance.
* <b>Note: This method requires a bean definition for the given name!</b>
* <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
* callbacks or perform any further initialization of the bean. This interface
* offers distinct, fine-grained operations for those purposes, for example
* {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
* callbacks are applied, if applicable to the configuration of the instance.
* @param existingBean the existing bean instance
* @param beanName the name of the bean definition in the bean factory
* (a bean definition of that name has to be available)
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
* if there is no bean definition with the given name
* @throws BeansException if applying the property values failed
* @see #autowireBeanProperties
*/
void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException; /**
* Initialize the given raw bean, applying factory callbacks
* such as {@code setBeanName} and {@code setBeanFactory},
* also applying all bean post processors (including ones which
* might wrap the given raw bean).
* <p>Note that no bean definition of the given name has to exist
* in the bean factory. The passed-in bean name will simply be used
* for callbacks but not checked against the registered bean definitions.
* @param existingBean the existing bean instance
* @param beanName the name of the bean, to be passed to it if necessary
* (only passed to {@link BeanPostProcessor BeanPostProcessors})
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if the initialization failed
*/
Object initializeBean(Object existingBean, String beanName) throws BeansException; /**
* Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean
* instance, invoking their {@code postProcessBeforeInitialization} methods.
* The returned bean instance may be a wrapper around the original.
* @param existingBean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessBeforeInitialization
*/
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException; /**
* Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean
* instance, invoking their {@code postProcessAfterInitialization} methods.
* The returned bean instance may be a wrapper around the original.
* @param existingBean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessAfterInitialization
*/
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException; /**
* Destroy the given bean instance (typically coming from {@link #createBean}),
* applying the {@link org.springframework.beans.factory.DisposableBean} contract as well as
* registered {@link DestructionAwareBeanPostProcessor DestructionAwareBeanPostProcessors}.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param existingBean the bean instance to destroy
*/
void destroyBean(Object existingBean); /**
* Resolve the specified dependency against the beans defined in this factory.
* @param descriptor the descriptor for the dependency
* @param beanName the name of the bean which declares the present dependency
* @param autowiredBeanNames a Set that all names of autowired beans (used for
* resolving the present dependency) are supposed to be added to
* @param typeConverter the TypeConverter to use for populating arrays and
* collections
* @return the resolved object, or {@code null} if none found
* @throws BeansException in dependency resolution failed
*/
Object resolveDependency(DependencyDescriptor descriptor, String beanName,
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException; }

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

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

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

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

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

 /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.beans.factory.config; import java.beans.PropertyEditor;
import java.security.AccessControlContext; import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.StringValueResolver; /**
* Configuration interface to be implemented by most bean factories. Provides
* facilities to configure a bean factory, in addition to the bean factory
* client methods in the {@link org.springframework.beans.factory.BeanFactory}
* interface.
*
* <p>This bean factory interface is not meant to be used in normal application
* code: Stick to {@link org.springframework.beans.factory.BeanFactory} or
* {@link org.springframework.beans.factory.ListableBeanFactory} for typical
* needs. This extended interface is just meant to allow for framework-internal
* plug'n'play and for special access to bean factory configuration methods.
*
* @author Juergen Hoeller
* @since 03.11.2003
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.beans.factory.ListableBeanFactory
* @see ConfigurableListableBeanFactory
*/
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry { /**
* Scope identifier for the standard singleton scope: "singleton".
* Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_SINGLETON = "singleton"; /**
* Scope identifier for the standard prototype scope: "prototype".
* Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_PROTOTYPE = "prototype"; /**
* Set the parent of this bean factory.
* <p>Note that the parent cannot be changed: It should only be set outside
* a constructor if it isn't available at the time of factory instantiation.
* @param parentBeanFactory the parent BeanFactory
* @throws IllegalStateException if this factory is already associated with
* a parent BeanFactory
* @see #getParentBeanFactory()
*/
void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException; /**
* Set the class loader to use for loading bean classes.
* Default is the thread context class loader.
* <p>Note that this class loader will only apply to bean definitions
* that do not carry a resolved bean class yet. This is the case as of
* Spring 2.0 by default: Bean definitions only carry bean class names,
* to be resolved once the factory processes the bean definition.
* @param beanClassLoader the class loader to use,
* or {@code null} to suggest the default class loader
*/
void setBeanClassLoader(ClassLoader beanClassLoader); /**
* Return this factory's class loader for loading bean classes.
*/
ClassLoader getBeanClassLoader(); /**
* Specify a temporary ClassLoader to use for type matching purposes.
* Default is none, simply using the standard bean ClassLoader.
* <p>A temporary ClassLoader is usually just specified if
* <i>load-time weaving</i> is involved, to make sure that actual bean
* classes are loaded as lazily as possible. The temporary loader is
* then removed once the BeanFactory completes its bootstrap phase.
* @since 2.5
*/
void setTempClassLoader(ClassLoader tempClassLoader); /**
* Return the temporary ClassLoader to use for type matching purposes,
* if any.
* @since 2.5
*/
ClassLoader getTempClassLoader(); /**
* Set whether to cache bean metadata such as given bean definitions
* (in merged fashion) and resolved bean classes. Default is on.
* <p>Turn this flag off to enable hot-refreshing of bean definition objects
* and in particular bean classes. If this flag is off, any creation of a bean
* instance will re-query the bean class loader for newly resolved classes.
*/
void setCacheBeanMetadata(boolean cacheBeanMetadata); /**
* Return whether to cache bean metadata such as given bean definitions
* (in merged fashion) and resolved bean classes.
*/
boolean isCacheBeanMetadata(); /**
* Specify the resolution strategy for expressions in bean definition values.
* <p>There is no expression support active in a BeanFactory by default.
* An ApplicationContext will typically set a standard expression strategy
* here, supporting "#{...}" expressions in a Unified EL compatible style.
* @since 3.0
*/
void setBeanExpressionResolver(BeanExpressionResolver resolver); /**
* Return the resolution strategy for expressions in bean definition values.
* @since 3.0
*/
BeanExpressionResolver getBeanExpressionResolver(); /**
* Specify a Spring 3.0 ConversionService to use for converting
* property values, as an alternative to JavaBeans PropertyEditors.
* @since 3.0
*/
void setConversionService(ConversionService conversionService); /**
* Return the associated ConversionService, if any.
* @since 3.0
*/
ConversionService getConversionService(); /**
* Add a PropertyEditorRegistrar to be applied to all bean creation processes.
* <p>Such a registrar creates new PropertyEditor instances and registers them
* on the given registry, fresh for each bean creation attempt. This avoids
* the need for synchronization on custom editors; hence, it is generally
* preferable to use this method instead of {@link #registerCustomEditor}.
* @param registrar the PropertyEditorRegistrar to register
*/
void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar); /**
* Register the given custom property editor for all properties of the
* given type. To be invoked during factory configuration.
* <p>Note that this method will register a shared custom editor instance;
* access to that instance will be synchronized for thread-safety. It is
* generally preferable to use {@link #addPropertyEditorRegistrar} instead
* of this method, to avoid for the need for synchronization on custom editors.
* @param requiredType type of the property
* @param propertyEditorClass the {@link PropertyEditor} class to register
*/
void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass); /**
* Initialize the given PropertyEditorRegistry with the custom editors
* that have been registered with this BeanFactory.
* @param registry the PropertyEditorRegistry to initialize
*/
void copyRegisteredEditorsTo(PropertyEditorRegistry registry); /**
* Set a custom type converter that this BeanFactory should use for converting
* bean property values, constructor argument values, etc.
* <p>This will override the default PropertyEditor mechanism and hence make
* any custom editors or custom editor registrars irrelevant.
* @see #addPropertyEditorRegistrar
* @see #registerCustomEditor
* @since 2.5
*/
void setTypeConverter(TypeConverter typeConverter); /**
* Obtain a type converter as used by this BeanFactory. This may be a fresh
* instance for each call, since TypeConverters are usually <i>not</i> thread-safe.
* <p>If the default PropertyEditor mechanism is active, the returned
* TypeConverter will be aware of all custom editors that have been registered.
* @since 2.5
*/
TypeConverter getTypeConverter(); /**
* Add a String resolver for embedded values such as annotation attributes.
* @param valueResolver the String resolver to apply to embedded values
* @since 3.0
*/
void addEmbeddedValueResolver(StringValueResolver valueResolver); /**
* Resolve the given embedded value, e.g. an annotation attribute.
* @param value the value to resolve
* @return the resolved value (may be the original value as-is)
* @since 3.0
*/
String resolveEmbeddedValue(String value); /**
* Add a new BeanPostProcessor that will get applied to beans created
* by this factory. To be invoked during factory configuration.
* <p>Note: Post-processors submitted here will be applied in the order of
* registration; any ordering semantics expressed through implementing the
* {@link org.springframework.core.Ordered} interface will be ignored. Note
* that autodetected post-processors (e.g. as beans in an ApplicationContext)
* will always be applied after programmatically registered ones.
* @param beanPostProcessor the post-processor to register
*/
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); /**
* Return the current number of registered BeanPostProcessors, if any.
*/
int getBeanPostProcessorCount(); /**
* Register the given scope, backed by the given Scope implementation.
* @param scopeName the scope identifier
* @param scope the backing Scope implementation
*/
void registerScope(String scopeName, Scope scope); /**
* Return the names of all currently registered scopes.
* <p>This will only return the names of explicitly registered scopes.
* Built-in scopes such as "singleton" and "prototype" won't be exposed.
* @return the array of scope names, or an empty array if none
* @see #registerScope
*/
String[] getRegisteredScopeNames(); /**
* Return the Scope implementation for the given scope name, if any.
* <p>This will only return explicitly registered scopes.
* Built-in scopes such as "singleton" and "prototype" won't be exposed.
* @param scopeName the name of the scope
* @return the registered Scope implementation, or {@code null} if none
* @see #registerScope
*/
Scope getRegisteredScope(String scopeName); /**
* Provides a security access control context relevant to this factory.
* @return the applicable AccessControlContext (never {@code null})
* @since 3.0
*/
AccessControlContext getAccessControlContext(); /**
* Copy all relevant configuration from the given other factory.
* <p>Should include all standard configuration settings as well as
* BeanPostProcessors, Scopes, and factory-specific internal settings.
* Should not include any metadata of actual bean definitions,
* such as BeanDefinition objects and bean name aliases.
* @param otherFactory the other BeanFactory to copy from
*/
void copyConfigurationFrom(ConfigurableBeanFactory otherFactory); /**
* Given a bean name, create an alias. We typically use this method to
* support names that are illegal within XML ids (used for bean names).
* <p>Typically invoked during factory configuration, but can also be
* used for runtime registration of aliases. Therefore, a factory
* implementation should synchronize alias access.
* @param beanName the canonical name of the target bean
* @param alias the alias to be registered for the bean
* @throws BeanDefinitionStoreException if the alias is already in use
*/
void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; /**
* Resolve all alias target names and aliases registered in this
* factory, applying the given StringValueResolver to them.
* <p>The value resolver may for example resolve placeholders
* in target bean names and even in alias names.
* @param valueResolver the StringValueResolver to apply
* @since 2.5
*/
void resolveAliases(StringValueResolver valueResolver); /**
* Return a merged BeanDefinition for the given bean name,
* merging a child bean definition with its parent if necessary.
* Considers bean definitions in ancestor factories as well.
* @param beanName the name of the bean to retrieve the merged definition for
* @return a (potentially merged) BeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean definition with the given name
* @since 2.5
*/
BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; /**
* Determine whether the bean with the given name is a FactoryBean.
* @param name the name of the bean to check
* @return whether the bean is a FactoryBean
* ({@code false} means the bean exists but is not a FactoryBean)
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.5
*/
boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException; /**
* Explicitly control the current in-creation status of the specified bean.
* For container-internal use only.
* @param beanName the name of the bean
* @param inCreation whether the bean is currently in creation
* @since 3.1
*/
void setCurrentlyInCreation(String beanName, boolean inCreation); /**
* Determine whether the specified bean is currently in creation.
* @param beanName the name of the bean
* @return whether the bean is currently in creation
* @since 2.5
*/
boolean isCurrentlyInCreation(String beanName); /**
* Register a dependent bean for the given bean,
* to be destroyed before the given bean is destroyed.
* @param beanName the name of the bean
* @param dependentBeanName the name of the dependent bean
* @since 2.5
*/
void registerDependentBean(String beanName, String dependentBeanName); /**
* Return the names of all beans which depend on the specified bean, if any.
* @param beanName the name of the bean
* @return the array of dependent bean names, or an empty array if none
* @since 2.5
*/
String[] getDependentBeans(String beanName); /**
* Return the names of all beans that the specified bean depends on, if any.
* @param beanName the name of the bean
* @return the array of names of beans which the bean depends on,
* or an empty array if none
* @since 2.5
*/
String[] getDependenciesForBean(String beanName); /**
* Destroy the given bean instance (usually a prototype instance
* obtained from this factory) according to its bean definition.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param beanName the name of the bean definition
* @param beanInstance the bean instance to destroy
*/
void destroyBean(String beanName, Object beanInstance); /**
* Destroy the specified scoped bean in the current target scope, if any.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param beanName the name of the scoped bean
*/
void destroyScopedBean(String beanName); /**
* Destroy all singleton beans in this factory, including inner beans that have
* been registered as disposable. To be called on shutdown of a factory.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
*/
void destroySingletons(); }

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

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

     /**
* 测试 ConfigurableBeanFactory
*/
@Test
public void testConfigurableBeanFactory() {
DefaultListableBeanFactory autowireCapableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory(); BeanFactoryTest_Bean2 bean1 = autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean2.class);
System.out.println(bean1); // BeanFactoryTest_Bean2{value='spring.BeanFactoryTest@1ca14537'} //EL有缓存所以要信create1个bean
StandardBeanExpressionResolver beanExpressionResolver = (StandardBeanExpressionResolver) autowireCapableBeanFactory.getBeanExpressionResolver();
beanExpressionResolver.setExpressionPrefix("#(");
beanExpressionResolver.setExpressionSuffix(")");
BeanFactoryTest_Bean3 bean3 = autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean3.class);
System.out.println(bean3); // BeanFactoryTest_Bean3{value='spring.BeanFactoryTest@1ca14537'}
} private static class BeanFactoryTest_Bean2 {
@Value("#{@myBeanFactoryTestBean.toString()}")
public String value; @Override
public String toString() {
return "BeanFactoryTest_Bean2{" +
"value='" + value + '\'' +
'}';
}
} private static class BeanFactoryTest_Bean3 { @Value("#(@myBeanFactoryTestBean.toString())")
public String value; @Override
public String toString() {
return "BeanFactoryTest_Bean3{" +
"value='" + value + '\'' +
'}';
}
}

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

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

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

另外还可以设置BeanPostProcessor.

         System.out.println(autowireCapableBeanFactory.getBeanPostProcessorCount()); //
autowireCapableBeanFactory.addBeanPostProcessor(new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor -> postProcessBeforeInitialization");
return bean;
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor -> postProcessAfterInitialization");
return bean;
}
});
System.out.println(autowireCapableBeanFactory.getBeanPostProcessorCount()); // 12
// MyBeanPostProcessor -> postProcessBeforeInitialization
// MyBeanPostProcessor -> postProcessAfterInitialization
BeanFactoryTest_Bean3 bean4 = autowireCapableBeanFactory.createBean(BeanFactoryTest_Bean3.class);

ConfigurableListableBeanFactory

 /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.beans.factory.config; import java.util.Iterator; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException; /**
* Configuration interface to be implemented by most listable bean factories.
* In addition to {@link ConfigurableBeanFactory}, it provides facilities to
* analyze and modify bean definitions, and to pre-instantiate singletons.
*
* <p>This subinterface of {@link org.springframework.beans.factory.BeanFactory}
* is not meant to be used in normal application code: Stick to
* {@link org.springframework.beans.factory.BeanFactory} or
* {@link org.springframework.beans.factory.ListableBeanFactory} for typical
* use cases. This interface is just meant to allow for framework-internal
* plug'n'play even when needing access to bean factory configuration methods.
*
* @author Juergen Hoeller
* @since 03.11.2003
* @see org.springframework.context.support.AbstractApplicationContext#getBeanFactory()
*/
public interface ConfigurableListableBeanFactory
extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory { /**
* Ignore the given dependency type for autowiring:
* for example, String. Default is none.
* @param type the dependency type to ignore
*/
void ignoreDependencyType(Class<?> type); /**
* Ignore the given dependency interface for autowiring.
* <p>This will typically be used by application contexts to register
* dependencies that are resolved in other ways, like BeanFactory through
* BeanFactoryAware or ApplicationContext through ApplicationContextAware.
* <p>By default, only the BeanFactoryAware interface is ignored.
* For further types to ignore, invoke this method for each type.
* @param ifc the dependency interface to ignore
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.context.ApplicationContextAware
*/
void ignoreDependencyInterface(Class<?> ifc); /**
* Register a special dependency type with corresponding autowired value.
* <p>This is intended for factory/context references that are supposed
* to be autowirable but are not defined as beans in the factory:
* e.g. a dependency of type ApplicationContext resolved to the
* ApplicationContext instance that the bean is living in.
* <p>Note: There are no such default types registered in a plain BeanFactory,
* not even for the BeanFactory interface itself.
* @param dependencyType the dependency type to register. This will typically
* be a base interface such as BeanFactory, with extensions of it resolved
* as well if declared as an autowiring dependency (e.g. ListableBeanFactory),
* as long as the given value actually implements the extended interface.
* @param autowiredValue the corresponding autowired value. This may also be an
* implementation of the {@link org.springframework.beans.factory.ObjectFactory}
* interface, which allows for lazy resolution of the actual target value.
*/
void registerResolvableDependency(Class<?> dependencyType, Object autowiredValue); /**
* Determine whether the specified bean qualifies as an autowire candidate,
* to be injected into other beans which declare a dependency of matching type.
* <p>This method checks ancestor factories as well.
* @param beanName the name of the bean to check
* @param descriptor the descriptor of the dependency to resolve
* @return whether the bean should be considered as autowire candidate
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
*/
boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
throws NoSuchBeanDefinitionException; /**
* Return the registered BeanDefinition for the specified bean, allowing access
* to its property values and constructor argument value (which can be
* modified during bean factory post-processing).
* <p>A returned BeanDefinition object should not be a copy but the original
* definition object as registered in the factory. This means that it should
* be castable to a more specific implementation type, if necessary.
* <p><b>NOTE:</b> This method does <i>not</i> consider ancestor factories.
* It is only meant for accessing local bean definitions of this factory.
* @param beanName the name of the bean
* @return the registered BeanDefinition
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* defined in this factory
*/
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; /**
* Return a unified view over all bean names managed by this factory.
* <p>Includes bean definition names as well as names of manually registered
* singleton instances, with bean definition names consistently coming first,
* analogous to how type/annotation specific retrieval of bean names works.
* @return the composite iterator for the bean names view
* @since 4.1.2
* @see #containsBeanDefinition
* @see #registerSingleton
* @see #getBeanNamesForType
* @see #getBeanNamesForAnnotation
*/
Iterator<String> getBeanNamesIterator(); /**
* Freeze all bean definitions, signalling that the registered bean definitions
* will not be modified or post-processed any further.
* <p>This allows the factory to aggressively cache bean definition metadata.
*/
void freezeConfiguration(); /**
* Return whether this factory's bean definitions are frozen,
* i.e. are not supposed to be modified or post-processed any further.
* @return {@code true} if the factory's configuration is considered frozen
*/
boolean isConfigurationFrozen(); /**
* Ensure that all non-lazy-init singletons are instantiated, also considering
* {@link org.springframework.beans.factory.FactoryBean FactoryBeans}.
* Typically invoked at the end of factory setup, if desired.
* @throws BeansException if one of the singleton beans could not be created.
* Note: This may have left the factory with some beans already initialized!
* Call {@link #destroySingletons()} for full cleanup in this case.
* @see #destroySingletons()
*/
void preInstantiateSingletons() throws BeansException; }

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

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

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

Spring 学习记录5 BeanFactory的更多相关文章

  1. Spring 学习记录6 BeanFactory(2)

    主题 除了Spring 学习记录5 BeanFactory 里写的几个接口外,BeanFactory的实现类还实现了一些其他接口,这篇文章主要介绍这些接口和实现类. 结构 DefaultListabl ...

  2. Spring 学习记录8 初识XmlWebApplicationContext(2)

    主题 接上文Spring 学习记录7 初识XmlWebApplicationContext refresh方法 refresh方法是定义在父类AbstractApplicationContext中的. ...

  3. 我的Spring学习记录(二)

    本篇就简单的说一下Bean的装配和AOP 本篇的项目是在上一篇我的Spring学习记录(一) 中项目的基础上进行开发的 1. 使用setter方法和构造方法装配Bean 1.1 前期准备 使用sett ...

  4. 我的Spring学习记录(四)

    虽然Spring管理这我们的Bean很方便,但是,我们需要使用xml配置大量的Bean信息,告诉Spring我们要干嘛,这还是挺烦的,毕竟当我们的Bean随之增多的话,xml的各种配置会让人很头疼. ...

  5. 我的Spring学习记录(五)

    在我的Spring学习记录(四)中使用了注解的方式对前面三篇做了总结.而这次,使用了用户登录及注册来对于本人前面四篇做一个应用案例,希望通过这个来对于我们的Spring的使用有一定的了解. 1. 程序 ...

  6. Spring 学习记录3 ConversionService

    ConversionService与Environment的关系 通过之前的学习(Spring 学习记录2 Environment),我已经Environment主要是负责解析properties和p ...

  7. Spring学习记录(九)---通过工厂方法配置bean

    1. 使用静态工厂方法创建Bean,用到一个工厂类 例子:一个Car类,有brand和price属性. package com.guigu.spring.factory; public class C ...

  8. Spring学习记录(七)---表达式语言-SpEL

    SpEL---Spring Expression Language:是一个支持运行时查询和操作对象图表达式语言.使用#{...}作为定界符,为bean属性动态赋值提供了便利. ①对于普通的赋值,用Sp ...

  9. 我的Spring学习记录(一)

    spring是一个框架,一个我理解为对象的大熔炉,它生产着各种bean,还可以对生产的对象进行加工. 这里有些概念需要理解一下,就是IOC和DI以及AOP,接下来,我们进入主题. spring简介 上 ...

随机推荐

  1. java大文件断点续传

    java两台服务器之间,大文件上传(续传),采用了Socket通信机制以及JavaIO流两个技术点,具体思路如下: 实现思路:1.服:利用ServerSocket搭建服务器,开启相应端口,进行长连接操 ...

  2. Oracle中用exp/imp命令快速导入导出数据

    from: http://blog.csdn.net/wangchunyu11155/article/details/53635602 [用 exp 数 据 导 出]: 1 将数据库TEST完全导出, ...

  3. WordCount运行详解

    1.MapReduce理论简介 1.1 MapReduce编程模型 MapReduce采用"分而治之"的思想,把对大规模数据集的操作,分发给一个主节点管理下的各个分节点共同完成,然 ...

  4. hadoop2.x常用端口、定义方法及默认端口、hadoop1.X端口对比

    问题导读: 1.DataNode的http服务的端口.ipc服务的端口分别是哪个? 2.NameNode的http服务的端口.ipc服务的端口分别是哪个? 3.journalnode的http服务的端 ...

  5. idea Java spring 入门 demo

    根据这个 来实现 理解 https://www.cnblogs.com/xing901022/p/3963962.html 这里没有说如何导入包,现在我们用 idea 来实现 新建项目结构后 RUN ...

  6. #ifndef/#define/#endif以及#if defined/#else/#endif使用详解

    1.#ifndef_WINDOWS_PLAYM4_H_      #define _WINDOWS_PLAYM4_H_ #endif 问题:想必很多人都看过"头文件中的 #ifndef/#d ...

  7. CentOS编译安装php7.2

    介绍: 久闻php7的速度以及性能那可是比php5系列的任何一版本都要快,具体性能有多好,建议还是先尝试下再说.如果你是升级或新安装,那你首先需要考虑php7和程序是否存在兼容性,如果程序是基于php ...

  8. CSU1632Repeated Substrings(后缀数组/最长公共前缀)

    题意就是求一个字符串的重复出现(出现次数>=2)的不同子串的个数. 标准解法是后缀数组.最长公共前缀的应用,对于样例aabaab,先将所有后缀排序: aab 3    aabaab 1    a ...

  9. 笔记:FastAdmin 之 jQuery 选择器 $("[name$='[]']", form) 学习

    笔记:FastAdmin 之 jQuery 选择器 $("[name$='[]']", form) 学习 $("[name$='[]']", form)这个是什 ...

  10. 题目1413:神秘元素 ——lis的元素是否唯一

    求序列的最长子序列中不可分割元素的数目.不可分割元素,肯定属于某一个最长子序列,首先做的就是把属于最长子序列的数提取出来,减小查找范围.怎么提取?可以用LIS(最长递增子序列)和LDS(最长递减子序列 ...