001/*
002 * Copyright 2002-2020 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.beans.factory;
018
019import org.springframework.beans.BeansException;
020import org.springframework.core.ResolvableType;
021import org.springframework.lang.Nullable;
022
023/**
024 * The root interface for accessing a Spring bean container.
025 *
026 * <p>This is the basic client view of a bean container;
027 * further interfaces such as {@link ListableBeanFactory} and
028 * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
029 * are available for specific purposes.
030 *
031 * <p>This interface is implemented by objects that hold a number of bean definitions,
032 * each uniquely identified by a String name. Depending on the bean definition,
033 * the factory will return either an independent instance of a contained object
034 * (the Prototype design pattern), or a single shared instance (a superior
035 * alternative to the Singleton design pattern, in which the instance is a
036 * singleton in the scope of the factory). Which type of instance will be returned
037 * depends on the bean factory configuration: the API is the same. Since Spring
038 * 2.0, further scopes are available depending on the concrete application
039 * context (e.g. "request" and "session" scopes in a web environment).
040 *
041 * <p>The point of this approach is that the BeanFactory is a central registry
042 * of application components, and centralizes configuration of application
043 * components (no more do individual objects need to read properties files,
044 * for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and
045 * Development" for a discussion of the benefits of this approach.
046 *
047 * <p>Note that it is generally better to rely on Dependency Injection
048 * ("push" configuration) to configure application objects through setters
049 * or constructors, rather than use any form of "pull" configuration like a
050 * BeanFactory lookup. Spring's Dependency Injection functionality is
051 * implemented using this BeanFactory interface and its subinterfaces.
052 *
053 * <p>Normally a BeanFactory will load bean definitions stored in a configuration
054 * source (such as an XML document), and use the {@code org.springframework.beans}
055 * package to configure the beans. However, an implementation could simply return
056 * Java objects it creates as necessary directly in Java code. There are no
057 * constraints on how the definitions could be stored: LDAP, RDBMS, XML,
058 * properties file, etc. Implementations are encouraged to support references
059 * amongst beans (Dependency Injection).
060 *
061 * <p>In contrast to the methods in {@link ListableBeanFactory}, all of the
062 * operations in this interface will also check parent factories if this is a
063 * {@link HierarchicalBeanFactory}. If a bean is not found in this factory instance,
064 * the immediate parent factory will be asked. Beans in this factory instance
065 * are supposed to override beans of the same name in any parent factory.
066 *
067 * <p>Bean factory implementations should support the standard bean lifecycle interfaces
068 * as far as possible. The full set of initialization methods and their standard order is:
069 * <ol>
070 * <li>BeanNameAware's {@code setBeanName}
071 * <li>BeanClassLoaderAware's {@code setBeanClassLoader}
072 * <li>BeanFactoryAware's {@code setBeanFactory}
073 * <li>EnvironmentAware's {@code setEnvironment}
074 * <li>EmbeddedValueResolverAware's {@code setEmbeddedValueResolver}
075 * <li>ResourceLoaderAware's {@code setResourceLoader}
076 * (only applicable when running in an application context)
077 * <li>ApplicationEventPublisherAware's {@code setApplicationEventPublisher}
078 * (only applicable when running in an application context)
079 * <li>MessageSourceAware's {@code setMessageSource}
080 * (only applicable when running in an application context)
081 * <li>ApplicationContextAware's {@code setApplicationContext}
082 * (only applicable when running in an application context)
083 * <li>ServletContextAware's {@code setServletContext}
084 * (only applicable when running in a web application context)
085 * <li>{@code postProcessBeforeInitialization} methods of BeanPostProcessors
086 * <li>InitializingBean's {@code afterPropertiesSet}
087 * <li>a custom init-method definition
088 * <li>{@code postProcessAfterInitialization} methods of BeanPostProcessors
089 * </ol>
090 *
091 * <p>On shutdown of a bean factory, the following lifecycle methods apply:
092 * <ol>
093 * <li>{@code postProcessBeforeDestruction} methods of DestructionAwareBeanPostProcessors
094 * <li>DisposableBean's {@code destroy}
095 * <li>a custom destroy-method definition
096 * </ol>
097 *
098 * @author Rod Johnson
099 * @author Juergen Hoeller
100 * @author Chris Beams
101 * @since 13 April 2001
102 * @see BeanNameAware#setBeanName
103 * @see BeanClassLoaderAware#setBeanClassLoader
104 * @see BeanFactoryAware#setBeanFactory
105 * @see org.springframework.context.ResourceLoaderAware#setResourceLoader
106 * @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher
107 * @see org.springframework.context.MessageSourceAware#setMessageSource
108 * @see org.springframework.context.ApplicationContextAware#setApplicationContext
109 * @see org.springframework.web.context.ServletContextAware#setServletContext
110 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
111 * @see InitializingBean#afterPropertiesSet
112 * @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName
113 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
114 * @see DisposableBean#destroy
115 * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName
116 */
117public interface BeanFactory {
118
119        /**
120         * Used to dereference a {@link FactoryBean} instance and distinguish it from
121         * beans <i>created</i> by the FactoryBean. For example, if the bean named
122         * {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
123         * will return the factory, not the instance returned by the factory.
124         */
125        String FACTORY_BEAN_PREFIX = "&";
126
127
128        /**
129         * Return an instance, which may be shared or independent, of the specified bean.
130         * <p>This method allows a Spring BeanFactory to be used as a replacement for the
131         * Singleton or Prototype design pattern. Callers may retain references to
132         * returned objects in the case of Singleton beans.
133         * <p>Translates aliases back to the corresponding canonical bean name.
134         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
135         * @param name the name of the bean to retrieve
136         * @return an instance of the bean
137         * @throws NoSuchBeanDefinitionException if there is no bean with the specified name
138         * @throws BeansException if the bean could not be obtained
139         */
140        Object getBean(String name) throws BeansException;
141
142        /**
143         * Return an instance, which may be shared or independent, of the specified bean.
144         * <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
145         * safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
146         * required type. This means that ClassCastException can't be thrown on casting
147         * the result correctly, as can happen with {@link #getBean(String)}.
148         * <p>Translates aliases back to the corresponding canonical bean name.
149         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
150         * @param name the name of the bean to retrieve
151         * @param requiredType type the bean must match; can be an interface or superclass
152         * @return an instance of the bean
153         * @throws NoSuchBeanDefinitionException if there is no such bean definition
154         * @throws BeanNotOfRequiredTypeException if the bean is not of the required type
155         * @throws BeansException if the bean could not be created
156         */
157        <T> T getBean(String name, Class<T> requiredType) throws BeansException;
158
159        /**
160         * Return an instance, which may be shared or independent, of the specified bean.
161         * <p>Allows for specifying explicit constructor arguments / factory method arguments,
162         * overriding the specified default arguments (if any) in the bean definition.
163         * @param name the name of the bean to retrieve
164         * @param args arguments to use when creating a bean instance using explicit arguments
165         * (only applied when creating a new instance as opposed to retrieving an existing one)
166         * @return an instance of the bean
167         * @throws NoSuchBeanDefinitionException if there is no such bean definition
168         * @throws BeanDefinitionStoreException if arguments have been given but
169         * the affected bean isn't a prototype
170         * @throws BeansException if the bean could not be created
171         * @since 2.5
172         */
173        Object getBean(String name, Object... args) throws BeansException;
174
175        /**
176         * Return the bean instance that uniquely matches the given object type, if any.
177         * <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
178         * but may also be translated into a conventional by-name lookup based on the name
179         * of the given type. For more extensive retrieval operations across sets of beans,
180         * use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
181         * @param requiredType type the bean must match; can be an interface or superclass
182         * @return an instance of the single bean matching the required type
183         * @throws NoSuchBeanDefinitionException if no bean of the given type was found
184         * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
185         * @throws BeansException if the bean could not be created
186         * @since 3.0
187         * @see ListableBeanFactory
188         */
189        <T> T getBean(Class<T> requiredType) throws BeansException;
190
191        /**
192         * Return an instance, which may be shared or independent, of the specified bean.
193         * <p>Allows for specifying explicit constructor arguments / factory method arguments,
194         * overriding the specified default arguments (if any) in the bean definition.
195         * <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
196         * but may also be translated into a conventional by-name lookup based on the name
197         * of the given type. For more extensive retrieval operations across sets of beans,
198         * use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
199         * @param requiredType type the bean must match; can be an interface or superclass
200         * @param args arguments to use when creating a bean instance using explicit arguments
201         * (only applied when creating a new instance as opposed to retrieving an existing one)
202         * @return an instance of the bean
203         * @throws NoSuchBeanDefinitionException if there is no such bean definition
204         * @throws BeanDefinitionStoreException if arguments have been given but
205         * the affected bean isn't a prototype
206         * @throws BeansException if the bean could not be created
207         * @since 4.1
208         */
209        <T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
210
211        /**
212         * Return a provider for the specified bean, allowing for lazy on-demand retrieval
213         * of instances, including availability and uniqueness options.
214         * @param requiredType type the bean must match; can be an interface or superclass
215         * @return a corresponding provider handle
216         * @since 5.1
217         * @see #getBeanProvider(ResolvableType)
218         */
219        <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
220
221        /**
222         * Return a provider for the specified bean, allowing for lazy on-demand retrieval
223         * of instances, including availability and uniqueness options.
224         * @param requiredType type the bean must match; can be a generic type declaration.
225         * Note that collection types are not supported here, in contrast to reflective
226         * injection points. For programmatically retrieving a list of beans matching a
227         * specific type, specify the actual bean type as an argument here and subsequently
228         * use {@link ObjectProvider#orderedStream()} or its lazy streaming/iteration options.
229         * @return a corresponding provider handle
230         * @since 5.1
231         * @see ObjectProvider#iterator()
232         * @see ObjectProvider#stream()
233         * @see ObjectProvider#orderedStream()
234         */
235        <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
236
237        /**
238         * Does this bean factory contain a bean definition or externally registered singleton
239         * instance with the given name?
240         * <p>If the given name is an alias, it will be translated back to the corresponding
241         * canonical bean name.
242         * <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
243         * be found in this factory instance.
244         * <p>If a bean definition or singleton instance matching the given name is found,
245         * this method will return {@code true} whether the named bean definition is concrete
246         * or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
247         * return value from this method does not necessarily indicate that {@link #getBean}
248         * will be able to obtain an instance for the same name.
249         * @param name the name of the bean to query
250         * @return whether a bean with the given name is present
251         */
252        boolean containsBean(String name);
253
254        /**
255         * Is this bean a shared singleton? That is, will {@link #getBean} always
256         * return the same instance?
257         * <p>Note: This method returning {@code false} does not clearly indicate
258         * independent instances. It indicates non-singleton instances, which may correspond
259         * to a scoped bean as well. Use the {@link #isPrototype} operation to explicitly
260         * check for independent instances.
261         * <p>Translates aliases back to the corresponding canonical bean name.
262         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
263         * @param name the name of the bean to query
264         * @return whether this bean corresponds to a singleton instance
265         * @throws NoSuchBeanDefinitionException if there is no bean with the given name
266         * @see #getBean
267         * @see #isPrototype
268         */
269        boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
270
271        /**
272         * Is this bean a prototype? That is, will {@link #getBean} always return
273         * independent instances?
274         * <p>Note: This method returning {@code false} does not clearly indicate
275         * a singleton object. It indicates non-independent instances, which may correspond
276         * to a scoped bean as well. Use the {@link #isSingleton} operation to explicitly
277         * check for a shared singleton instance.
278         * <p>Translates aliases back to the corresponding canonical bean name.
279         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
280         * @param name the name of the bean to query
281         * @return whether this bean will always deliver independent instances
282         * @throws NoSuchBeanDefinitionException if there is no bean with the given name
283         * @since 2.0.3
284         * @see #getBean
285         * @see #isSingleton
286         */
287        boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
288
289        /**
290         * Check whether the bean with the given name matches the specified type.
291         * More specifically, check whether a {@link #getBean} call for the given name
292         * would return an object that is assignable to the specified target type.
293         * <p>Translates aliases back to the corresponding canonical bean name.
294         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
295         * @param name the name of the bean to query
296         * @param typeToMatch the type to match against (as a {@code ResolvableType})
297         * @return {@code true} if the bean type matches,
298         * {@code false} if it doesn't match or cannot be determined yet
299         * @throws NoSuchBeanDefinitionException if there is no bean with the given name
300         * @since 4.2
301         * @see #getBean
302         * @see #getType
303         */
304        boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
305
306        /**
307         * Check whether the bean with the given name matches the specified type.
308         * More specifically, check whether a {@link #getBean} call for the given name
309         * would return an object that is assignable to the specified target type.
310         * <p>Translates aliases back to the corresponding canonical bean name.
311         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
312         * @param name the name of the bean to query
313         * @param typeToMatch the type to match against (as a {@code Class})
314         * @return {@code true} if the bean type matches,
315         * {@code false} if it doesn't match or cannot be determined yet
316         * @throws NoSuchBeanDefinitionException if there is no bean with the given name
317         * @since 2.0.1
318         * @see #getBean
319         * @see #getType
320         */
321        boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
322
323        /**
324         * Determine the type of the bean with the given name. More specifically,
325         * determine the type of object that {@link #getBean} would return for the given name.
326         * <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
327         * as exposed by {@link FactoryBean#getObjectType()}. This may lead to the initialization
328         * of a previously uninitialized {@code FactoryBean} (see {@link #getType(String, boolean)}).
329         * <p>Translates aliases back to the corresponding canonical bean name.
330         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
331         * @param name the name of the bean to query
332         * @return the type of the bean, or {@code null} if not determinable
333         * @throws NoSuchBeanDefinitionException if there is no bean with the given name
334         * @since 1.1.2
335         * @see #getBean
336         * @see #isTypeMatch
337         */
338        @Nullable
339        Class<?> getType(String name) throws NoSuchBeanDefinitionException;
340
341        /**
342         * Determine the type of the bean with the given name. More specifically,
343         * determine the type of object that {@link #getBean} would return for the given name.
344         * <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
345         * as exposed by {@link FactoryBean#getObjectType()}. Depending on the
346         * {@code allowFactoryBeanInit} flag, this may lead to the initialization of a previously
347         * uninitialized {@code FactoryBean} if no early type information is available.
348         * <p>Translates aliases back to the corresponding canonical bean name.
349         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
350         * @param name the name of the bean to query
351         * @param allowFactoryBeanInit whether a {@code FactoryBean} may get initialized
352         * just for the purpose of determining its object type
353         * @return the type of the bean, or {@code null} if not determinable
354         * @throws NoSuchBeanDefinitionException if there is no bean with the given name
355         * @since 5.2
356         * @see #getBean
357         * @see #isTypeMatch
358         */
359        @Nullable
360        Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
361
362        /**
363         * Return the aliases for the given bean name, if any.
364         * <p>All of those aliases point to the same bean when used in a {@link #getBean} call.
365         * <p>If the given name is an alias, the corresponding original bean name
366         * and other aliases (if any) will be returned, with the original bean name
367         * being the first element in the array.
368         * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
369         * @param name the bean name to check for aliases
370         * @return the aliases, or an empty array if none
371         * @see #getBean
372         */
373        String[] getAliases(String name);
374
375}