ApplicationContextAware如何在Spring中运行? [英] How does ApplicationContextAware work in Spring?
问题描述
在spring中,如果bean实现了 ApplicationContextAware
,那么它就能够访问 applicationContext
。因此它能够获得其他豆类。
,例如
In spring, if a bean implements ApplicationContextAware
, then it is able to access the applicationContext
. Therefore it is able to get other beans.
e.g.
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)
可以得到beanname。
Then SpringContextUtil.getApplicationContext.getBean("name")
can get the bean "name".
为此,我们应该把这个 SpringContextUtil
在 applications.xml
中,例如
To do this, we should put this SpringContextUtil
inside the applications.xml
, e.g.
<bean class="com.util.SpringContextUtil" />
此处bean SpringContextUtil
不包括属性 applicationContext
。我想当spring bean初始化时,会设置此属性。但这是怎么做到的?如何调用方法 setApplicationContext
?
Here the bean SpringContextUtil
doesn't include the property applicationContext
. I guess when spring bean initialize, this property is set. But how is this done? How does the method setApplicationContext
get called?
推荐答案
当spring实例化bean时,它寻找几个接口,如 ApplicationContextAware
和 InitializingBean
。如果找到它们,则调用这些方法。例如。 (非常简化)
When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware
and InitializingBean
. If they are found, the methods are invoked. E.g. (very simplified)
Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(ctx);
}
请注意,在较新的版本中,最好使用注释,而不是实施特定于弹簧的接口。现在你只需使用:
Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:
@Inject // or @Autowired
private ApplicationContext ctx;
这篇关于ApplicationContextAware如何在Spring中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!