在spring中,如果bean实现了ApplicationContextAware
,那么它就能够访问applicationContext
。因此,它能够获得其他bean。例如:
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
然后,SpringContextUtil.getApplicationContext.getBean("name")
可以获得bean "name“。
要做到这一点,我们应该将这个SpringContextUtil
放在applications.xml
中,例如
<bean class="com.util.SpringContextUtil" />
在这里,bean SpringContextUtil
没有包含属性applicationContext
。我猜当spring bean初始化时,这个属性就被设置了。但是如何做到这一点呢?如何调用setApplicationContext
方法?
发布于 2014-02-04 21:02:38
当spring实例化beans时,它会寻找一些接口,比如ApplicationContextAware
和InitializingBean
。如果找到它们,则调用这些方法。例如(非常简单)
Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(ctx);
}
请注意,在较新的版本中,使用注释可能比实现特定于spring的接口更好。现在您可以简单地使用:
@Inject // or @Autowired
private ApplicationContext ctx;
发布于 2016-07-29 15:52:42
ApplicationContextAware接口,当前应用程序上下文,您可以通过它调用spring容器服务。我们可以通过类中的以下方法获得当前注入的applicationContext实例
public void setApplicationContext(ApplicationContext context) throws BeansException.
https://stackoverflow.com/questions/21553120
复制相似问题