Java 为什么类需要访问Spring上下文?
我发现Springbean和其他常规类都可以访问Spring应用程序上下文 我想知道为什么一个类必须处理Spring上下文。我的理解是,在主要方法中,您引导您的应用程序,并且从这一点开始,所有内容都由Spring连接Java 为什么类需要访问Spring上下文?,java,spring,dependency-injection,Java,Spring,Dependency Injection,我发现Springbean和其他常规类都可以访问Spring应用程序上下文 我想知道为什么一个类必须处理Spring上下文。我的理解是,在主要方法中,您引导您的应用程序,并且从这一点开始,所有内容都由Spring连接 如果是这种情况,那么main方法应该是您需要ApplicationContext的唯一位置。还有哪些真正的案例需要Spring上下文来完成工作?事实上,有很多这样的用例。假设您想要编写一个验证器类,该类需要由某个服务bean访问。现在,已经通过Spring上下文配置了authent
如果是这种情况,那么main方法应该是您需要ApplicationContext的唯一位置。还有哪些真正的案例需要Spring上下文来完成工作?事实上,有很多这样的用例。假设您想要编写一个验证器类,该类需要由某个服务bean访问。现在,已经通过Spring上下文配置了authenticator类。那么,您如何访问该bean?答案是通过Spring应用程序上下文:
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不是答案,因为它将重复所有配置。通常bean不需要直接访问
ApplicationContext
然而,有些情况下需要直接访问。例如:
- 要在运行时访问由其名称标识的bean,请执行以下操作:
class MyClass implements ApplicationContextAware { ... public void execute(String actionName) { Action action = applicationContext.getBean(actionName); action.execute(); } ... }
Bean bean = applicationContext.getBean("myBean", "foo", "bar");
- 要在运行时将自定义参数传递给
-作用域bean的构造函数,请执行以下操作:prototype
class MyClass implements ApplicationContextAware { ... public void execute(String actionName) { Action action = applicationContext.getBean(actionName); action.execute(); } ... }
请注意,如果Bean bean = applicationContext.getBean("myBean", "foo", "bar");
的构造函数不需要在运行时传递自定义参数,则可以插入Bean
ObjectFactory
- 使用
触发第三方对象的自动关联AutowireCapableBeanFactory
验证器
bean连接到MyClass
可以更好地解决这个问题,不是吗?在这种情况下使用ApplicationContextAware
不会增加任何好处,而且会使您的类更难测试。我只是指出一个明显的例子。也许我选择得不好。:)