Reputation: 128
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
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
:
A
in is root application context, B
must be declared in root application contextA
in is servlet application context, B
can be declared either in servlet application context or in root oneBut 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
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