是否有一种方法可以在Spring应用程序中静态/全局地请求ApplicationContext的副本?

假设主类启动并初始化了应用程序上下文,它是否需要通过调用堆栈向下传递给任何需要它的类,或者类是否有一种方法来请求先前创建的上下文?(我假设它必须是单例的?)


当前回答

方法1:您可以通过实现ApplicationContextAware接口来注入ApplicationContext。参考链接。

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

方法2:在任何spring托管bean中自动装配应用程序上下文。

@Component
public class SpringBean {
  @Autowired
  private ApplicationContext appContext;
}

参考链接。

其他回答

看一下ContextSingletonBeanFactoryLocator。它提供静态访问器来获取Spring的上下文,假设它们已经以某种方式注册。

它并不漂亮,而且可能比您想要的还要复杂,但它是有效的。

在Spring应用程序中有许多获取应用程序上下文的方法。这些因素如下:

通过ApplicationContextAware: 进口org.springframework.beans.BeansException; 进口org.springframework.context.ApplicationContext; 进口org.springframework.context.ApplicationContextAware; 公共类AppContextProvider实现了ApplicationContextAware { private ApplicationContext; @Override setApplicationContext(ApplicationContext)抛出BeansException { 这一点。applicationContext = applicationContext; } }

这里setApplicationContext(ApplicationContext ApplicationContext)方法将获得ApplicationContext

ApplicationContextAware: 接口,由希望被通知的任何对象实现 它运行的ApplicationContext的。实现此接口 例如,当一个对象需要访问一组 合作bean。

通过Autowired的: @ autowired private ApplicationContext;

这里@Autowired关键字将提供applicationContext。自动连线有一些问题。这将在单元测试时产生问题。

即使在添加了@Autowire之后,如果你的类不是一个RestController或Configuration class, applicationContext对象仍然是空的。尝试用下面创建新类,它工作正常:

@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

然后,你可以在同一个类中根据你的需要实现一个getter方法,比如通过:

    applicationContext.getBean(String serviceName,Interface.Class)

如果需要访问容器的对象是容器中的bean,则只需实现BeanFactoryAware或ApplicationContextAware接口。

如果容器外部的对象需要访问容器,我为spring容器使用了标准的GoF单例模式。这样,您的应用程序中只有一个单例bean,其余的都是容器中的单例bean。

在你执行任何其他建议之前,问自己这些问题…

为什么我要获取ApplicationContext? 我是否有效地使用ApplicationContext作为服务定位器? 我可以完全避免访问ApplicationContext吗?

在某些类型的应用程序(例如Web应用程序)中,这些问题的答案比在其他应用程序中更容易,但无论如何都值得一问。

访问ApplicationContext确实违反了整个依赖注入原则,但有时您没有太多选择。