Jaynil
Jaynil

Reputation: 128

beanFactory.getBean not loading bean

I am having a service class annotated with @Service annotation as Class A and I am implementing BeanFactoryAware in A. Now I am setting the BeanFactory using setBeanFactory method. I am trying to load a bean "B" using beanFactory.getBean method. Now in this case is it compulsory to define "B" bean in application-context.xml file?

Upvotes: 2

Views: 1979

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149075

If you inject the BeanFactory in class A, and then try to get bean b with beanFactory.getBean, bean b must be declared in the same application context as bean a, or in a parent of this application context.

Concrete use cases for a standard web application with a root application context and a servlet application context for a DispatcherServlet :

  • if A in is root application context, B must be declared in root application context
  • if A in is servlet application context, B can be declared either in servlet application context or in root one

But if the only reason of that is to use bean B in bean A it would be better to directly inject it instead of the BeanFactory (with same rules for the application contextes)

Upvotes: 2

Xstian
Xstian

Reputation: 8282

There are 2 ways ..

first one

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="b" class="your.package.B" />

</beans>

second one

Spring will scan this folder and find out the bean (annotated with @Component, @Service, @Repository, etc) and register it

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="your.package" />

</beans>

I suggest to use..

public class Application implements ApplicationContextAware{

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException    {
        this.applicationContext = applicationContext;
    }

}

and the method

B b = applicationContext.getBean("b");

Upvotes: 1

Related Questions