Java Code Examples for org.springframework.beans.factory.BeanFactory

Following code examples demonstrate how to use org.springframework.beans.factory.BeanFactoryfrom spring-framework. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.springframework.beans.factory.BeanFactoryand various code implementation of this class.

	protected ObjectFactory<Object> createInstance() {
		BeanFactory beanFactory = getBeanFactory();
		Assert.state(beanFactory != null, "No BeanFactory available");
		Assert.state(this.targetBeanName != null, "No target bean name specified");
		return new TargetBeanObjectFactory(beanFactory, this.targetBeanName);
	} 


		public BeanFactory get() {

			BeanFactory beanFactory = this.beanFactory.get();

			Assert.state(beanFactory != null, UNINITIALIZED_BEAN_FACTORY_REFERENCE_MESSAGE);

			return beanFactory;
		} 

	public GemfireBeanFactoryLocator withBeanName(String beanName) {
		setBeanName(beanName);
		return this;
	} 

	public static GemfireBeanFactoryLocator newBeanFactoryLocator(BeanFactory beanFactory, String associatedBeanName) {

		Assert.isTrue(beanFactory == null || StringUtils.hasText(associatedBeanName),
			"associatedBeanName must be specified when BeanFactory is not null");

		GemfireBeanFactoryLocator beanFactoryLocator = new GemfireBeanFactoryLocator();

		beanFactoryLocator.setBeanFactory(beanFactory);
		beanFactoryLocator.setBeanName(associatedBeanName);
		beanFactoryLocator.afterPropertiesSet();

		return beanFactoryLocator;
	} 

	protected static synchronized BeanFactory resolveSingleBeanFactory() {

		if (!BEAN_FACTORIES.isEmpty()) {

			boolean allTheSameBeanFactory = true;

			BeanFactory currentBeanFactory = null;

			for (BeanFactory beanFactory : BEAN_FACTORIES.values()) {

				allTheSameBeanFactory &= nullOrEquals(currentBeanFactory, beanFactory);
				currentBeanFactory = beanFactory;

				if (!allTheSameBeanFactory) {
					break;
				}
			}

			Assert.state(allTheSameBeanFactory,
				String.format("BeanFactory key must be specified when more than one BeanFactory %s is registered",
					new TreeSet(BEAN_FACTORIES.keySet()).toString()));

			return BEAN_FACTORIES.values().iterator().next();
		}

		return null;
	} 

	protected static BeanFactory resolveBeanFactory(String beanFactoryKey) {

		BeanFactory beanFactory = BEAN_FACTORIES.get(beanFactoryKey);

		Assert.isTrue(BEAN_FACTORIES.isEmpty() || beanFactory != null,
			String.format("BeanFactory for key [%s] was not found", beanFactoryKey));

		return beanFactory;
	} 

	public void afterPropertiesSet() {

		BeanFactory beanFactory = getBeanFactory();

		registerAliases(resolveAndInitializeBeanNamesWithAliases(beanFactory), beanFactory);
	} 

	protected static synchronized void registerAliases(Set<String> names, BeanFactory beanFactory) {

		Set<String> safeNames = nullSafeSet(names);

		Assert.isTrue(safeNames.isEmpty() || beanFactory != null,
			"BeanFactory must not be null when aliases are specified");

		for (String name : safeNames) {

			BeanFactory existingBeanFactory = BEAN_FACTORIES.putIfAbsent(name, beanFactory);

			Assert.isTrue(nullOrEquals(existingBeanFactory, beanFactory),
				String.format("BeanFactory reference already exists for key [%s]", name));
		}
	} 

	public BeanFactory useBeanFactory(String beanFactoryKey) {
		return newBeanFactoryReference(StringUtils.hasText(beanFactoryKey)
			? resolveBeanFactory(beanFactoryKey) : resolveSingleBeanFactory()).get();
	} 

    public static final BeanFactory getBeanFactory() {

        String classPath = "org/third/spring/basic/";
        org.springframework.context.ApplicationContext appContext = new org.springframework.context.support.ClassPathXmlApplicationContext(
                new String[] { classPath + CONIG_FILE });
        org.springframework.beans.factory.BeanFactory factory3 = (BeanFactory) appContext;
        return factory3;
    } 

    public static void main(String[] args) {
        BeanFactory bf = getBeanFactory();
        System.out.println(bf.getBean("complexBean"));

    } 

Advertisement
Javadoc
The root interface for accessing a Spring bean container. This is the basic client view of a bean co

ntainer; further interfaces such as ListableBeanFactory and org.springframework.beans.factory.config.ConfigurableBeanFactory are available for specific purposes.

This interface is implemented by objects that hold a number of bean definitions, each uniquely identified by a String name. Depending on the bean definition, the factory will return either an independent instance of a contained object (the Prototype design pattern), or a single shared instance (a superior alternative to the Singleton design pattern, in which the instance is a singleton in the scope of the factory). Which type of instance will be returned depends on the bean factory configuration: the API is the same. Since Spring 2.0, further scopes are available depending on the concrete application context (e.g. "request" and "session" scopes in a web environment).

The point of this approach is that the BeanFactory is a central registry of application components, and centralizes configuration of application components (no more do individual objects need to read properties files, for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and Development" for a discussion of the benefits of this approach.

Note that it is generally better to rely on Dependency Injection ("push" configuration) to configure application objects through setters or constructors, rather than use any form of "pull" configuration like a BeanFactory lookup. Spring's Dependency Injection functionality is implemented using this BeanFactory interface and its subinterfaces.

Normally a BeanFactory will load bean definitions stored in a configuration source (such as an XML document), and use the org.springframework.beans package to configure the beans. However, an implementation could simply return Java objects it creates as necessary directly in Java code. There are no constraints on how the definitions could be stored: LDAP, RDBMS, XML, properties file, etc. Implementations are encouraged to support references amongst beans (Dependency Injection).

In contrast to the methods in ListableBeanFactory, all of the operations in this interface will also check parent factories if this is a HierarchicalBeanFactory. If a bean is not found in this factory instance, the immediate parent factory will be asked. Beans in this factory instance are supposed to override beans of the same name in any parent factory.

Bean factory implementations should support the standard bean lifecycle interfaces as far as possible. The full set of initialization methods and their standard order is: BeanNameAware's setBeanName BeanClassLoaderAware's setBeanClassLoader BeanFactoryAware's setBeanFactory EnvironmentAware's setEnvironment EmbeddedValueResolverAware's setEmbeddedValueResolver ResourceLoaderAware's setResourceLoader (only applicable when running in an application context) ApplicationEventPublisherAware's setApplicationEventPublisher (only applicable when running in an application context) MessageSourceAware's setMessageSource (only applicable when running in an application context) ApplicationContextAware's setApplicationContext (only applicable when running in an application context) ServletContextAware's setServletContext (only applicable when running in a web application context) postProcessBeforeInitialization methods of BeanPostProcessors InitializingBean's afterPropertiesSet a custom init-method definition postProcessAfterInitialization methods of BeanPostProcessors

On shutdown of a bean factory, the following lifecycle methods apply: postProcessBeforeDestruction methods of DestructionAwareBeanPostProcessors DisposableBean's destroy a custom destroy-method definition @author Rod Johnson @author Juergen Hoeller @author Chris Beams @since 13 April 2001 @see BeanNameAware#setBeanName @see BeanClassLoaderAware#setBeanClassLoader @see BeanFactoryAware#setBeanFactory @see org.springframework.context.ResourceLoaderAware#setResourceLoader @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher @see org.springframework.context.MessageSourceAware#setMessageSource @see org.springframework.context.ApplicationContextAware#setApplicationContext @see org.springframework.web.context.ServletContextAware#setServletContext @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization @see InitializingBean#afterPropertiesSet @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization @see DisposableBean#destroy @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName

Read More
Advertisement