有什么方法可以在 Spring 的 bean 配置文件中引用当前应用程序上下文吗?
我正在尝试做这样的事情:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="some-bean-name" class="com.company.SomeClass">
<constructor-arg>
<!-- obviously this isn't right -->
<bean ref=#{this}/>
</constructor-arg>
</bean>
问题是 SomeClass
在其构造函数中需要一个 ApplicationContext 实例。有没有办法获取正在加载 bean 的 ApplicationContext 的引用?我知道我可以在 XML 中完成所有加载,但这并不是我想要的,因为我需要在我的 java 代码中加载 bean。
最佳答案
您是否考虑过实现 ApplicationContextAware
?它不会出现在构造函数中,但它确实发生在 init()
调用之前,并且会在填充 bean 属性之后立即发生。
Invoked after population of normal bean properties but before an init callback such as InitializingBean.afterPropertiesSet() or a custom init-method. Invoked after ResourceLoaderAware.setResourceLoader(org.springframework.core.io.ResourceLoader), ApplicationEventPublisherAware.setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) and MessageSourceAware, if applicable.
public class SomeClass implements ApplicationContextAware {
//your class definition
private ApplicationContext myContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
myContext = context;
//load beans here maybe?
}
}
如果使用 Spring 2.5 或更高版本,您也可以只@Autowire(d)
它。
public class SomeClass {
//your class definition
@Autowired
private ApplicationContext myContext;
}
当然,执行其中任何一个都会将您的代码绑定(bind)到 Spring。
关于java - "this"Spring XML 中 applicationcontext 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7892667/