我看到 Spring bean 和其他常规类都可以访问 Spring 应用程序上下文。
我想知道为什么一个类必须处理 Spring 上下文。我的理解是,在 main 方法中,您引导您的应用程序,并且从那时起的所有内容都由 Spring 连接。
如果是这种情况,main 方法应该是唯一需要 ApplicationContext 的地方。您需要 Spring 上下文来完成工作的其他真实案例是什么?
我看到 Spring bean 和其他常规类都可以访问 Spring 应用程序上下文。
我想知道为什么一个类必须处理 Spring 上下文。我的理解是,在 main 方法中,您引导您的应用程序,并且从那时起的所有内容都由 Spring 连接。
如果是这种情况,main 方法应该是唯一需要 ApplicationContext 的地方。您需要 Spring 上下文来完成工作的其他真实案例是什么?
通常beans不需要ApplicationContext
直接访问。
但是,在某些情况下需要直接访问。例如:
要在运行时访问由其名称标识的 bean:
class MyClass implements ApplicationContextAware {
...
public void execute(String actionName) {
Action action = applicationContext.getBean(actionName);
action.execute();
}
...
}
在运行时将自定义参数传递给prototype
-scoped bean 的构造函数:
Bean bean = applicationContext.getBean("myBean", "foo", "bar");
请注意,如果Bean
的构造函数不需要在运行时传递自定义参数,则可以注入ObjectFactory<Bean>
。
使用 触发第三方对象的自动装配AutowireCapableBeanFactory
。
事实上,有很多这样的用例。假设您要编写一个身份验证器类,该类需要被某个服务 bean 访问。现在,已经通过 Spring 上下文配置了身份验证器类。那么,您如何访问该 bean?答案是通过 Spring ApplicationContext:
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 不是答案,因为它会重复所有配置。