Java bean中是否需要ApplicationContext对象引用?

Java bean中是否需要ApplicationContext对象引用?,java,spring,Java,Spring,在bean中引用applicationContext有什么可能的用途?将告诉您我们的一个使用经验。我们使用应用程序上下文获取实现特定接口的bean集合: public class MyBean implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) {

在bean中引用applicationContext有什么可能的用途?

将告诉您我们的一个使用经验。我们使用应用程序上下文获取实现特定接口的bean集合:

public class MyBean implements ApplicationListener<ContextRefreshedEvent> {



    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        Collection<IMyInterface> implementors = context.getBeansOfType(IMyInterface.class).values();

    }
公共类MyBean实现ApplicationListener{
@凌驾
ApplicationEvent(ContextRefreshedEvent事件)上的公共无效{
ApplicationContext context=event.getApplicationContext();
集合实现者=context.getBeansOfType(IMyInterface.class).values();
}

}

在编写基础结构代码时,使用
ApplicationContext
ConfigurableApplicationContext
的句柄非常有用。例如,如果您想编写一个服务定位器来查找实现接口的所有bean,您可以

@Autowired
private ApplicationContext applicationContext;

@PostConstruct
public void addFooServices() {

    for (... : this.applicationContext.getBeansOfType(FooService.class)) {
        // do something with each
}
这些类型的使用正在减少,因为您现在(3.2,如果不是更早的话)只需注入

@Autowired
private List<FooService> fooServices;
@Autowired
私人列表服务;

但是,有时您仍然可以使用容器,例如从JMX触发容器刷新,或其他黑客行为。

如果您想动态获取bean实例,但不想将自己绑定到注释?如果没有明显的注释,从bean获取上下文?对我来说,如果你想做一些更复杂的依赖注入,或者需要一点处理,而不是像在setter上设置Bean或者调用工厂这样简单的情况,我看不出这有什么用处?哦!您正在使用条件DI编写框架,但在通过注释支持条件DI之前,您使用的是spring版本@CodeChimp:假设bean中有一个getX()方法。该方法检查:如果x==null,则使用applicationContext获取bean。因此,在本例中,使用applicationContext获取bean是一个好主意,而不仅仅是自动连接bean?OP是问您为什么要这样做,而不是怎么做。@CodeChimp我从另一个角度理解了这个问题。相应地更新了我的答案