我发现Spring bean和其他常规类都可以访问spring应用程序上下文。
我想知道为什么一个类必须处理Spring上下文。我的理解是,在main方法中,你引导你的应用程序,从那一点起的所有东西都由Spring连接。
如果是这种情况,main方法应该是您需要ApplicationContext的唯一地方。您需要Spring上下文来完成工作的其他真实案例是什么?
答案 0 :(得分:4)
通常bean不需要直接访问ApplicationContext
。
但是,有些情况下需要直接访问。例如:
要在运行时访问由其名称标识的bean:
class MyClass implements ApplicationContextAware {
...
public void execute(String actionName) {
Action action = applicationContext.getBean(actionName);
action.execute();
}
...
}
在运行时将自定义参数传递给prototype
- 作用域bean的constuctor:
Bean bean = applicationContext.getBean("myBean", "foo", "bar");
请注意,如果Bean
的构造函数不需要在运行时传递自定义参数,则可以注入ObjectFactory<Bean>
。
使用AutowireCapableBeanFactory
触发第三方对象的自动装配。
答案 1 :(得分:0)
class MyClass implements ApplicationContextAware {
private ApplicationContext context;
@Override
void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
public void execute() {
Authenticator authenticator = context.getBean("authenticator", Authenticator.class);
if (!authenticator.authenticate()) {
//do some stuff
} else {
//do some other stuff
}
}
}
请务必注意,您不能通过除应用程序上下文之外的任何方式访问配置的bean。此外,实例化另一个ApplicationContext不是答案,因为它将重复所有配置。