mongiesama
mongiesama

Reputation: 365

Why is programmatically created bean not available in the application context

I have a Spring 3.0.7 application, in which I have to initialize some beans in Java rather than xml. I'm trying to figure out why the beans I initialize can't be retrieved from the application context.

When the below code executes, I get "org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'beanName' is defined" when I call beanFactory.getBean("beanName").

public class BeanToCreateBeans implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        BeanObject bean = new BeanObject();
        beanFactory.initializeBean(bean, "beanName");
        System.out.println("bean in the application: " + beanFactory.getBean("beanName"));
    }
}

Why can't the bean be retrieved after creating it? I need to be able to create the bean and add it to the application context.

Update: As the answer states, my code isn't actually registering the bean, which answers the question I posed. So, in order to make my code work the way I wanted, it looks like:

public class BeanToCreateBeans implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry bdr) throws BeansException {
        BeanDefinition definition = new RootBeanDefinition(BeanObject.class);
        bdr.registerBeanDefinition("beanName", definition);
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        BeanObject bean = new BeanObject();
        beanFactory.initializeBean(bean, "beanName");
        System.out.println("bean in the application: " + beanFactory.getBean("beanName"));
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

Upvotes: 1

Views: 1489

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

AutowireCapableBeanFactory#initializeBean(Object, String) doesn't add a bean to a context or bean factory. The javadoc states

Initialize the given raw bean, applying factory callbacks such as setBeanName and setBeanFactory, also applying all bean post processors (including ones which might wrap the given raw bean).

It basically just processes the object you pass to it as if it was a bean initialized as part of the ApplicationContext. Notice that the method returns an Object, the result of the initialization.

Returns: the bean instance to use, either the original or a wrapped one

Upvotes: 1

Related Questions