简体   繁体   English

在春季访问缓存的ApplicationContext

[英]Accessing cached ApplicationContext in spring

I need to fetch a singleton bean from same ApplicationContext twice in 2 different classes. 我需要在2个不同的类中两次从同一ApplicationContext中获取一个singleton bean。

Example snippet : 片段示例:

CLass A {
  public void foo(){
    ApplicationContext context = new ClassPathXmlApplicationContext("common.spring.xml");
    MyParametrizedSingletonClass myParametrizedSingletonClass = (MyParametrizedSingletonClass) context.getBean("myParametrizedSingletonClass");
    // do more stuff..
  }
CLass B {
  public void bar(){
    ApplicationContext context = new ClassPathXmlApplicationContext("common.spring.xml");
    MyParametrizedSingletonClass myParametrizedSingletonClass = (MyParametrizedSingletonClass) context.getBean("myParametrizedSingletonClass");
    // do more stuff..
  }

Since MyParametrizedSingletonClass is a singletom it if its constructor is called more than once for same constructor arguments it throws error. 由于MyParametrizedSingletonClass是单例,因此如果针对相同的构造函数参数多次调用其构造函数,则会引发错误。

How do I cache and reuse ApplicationContext with spring? 如何使用Spring缓存和重用ApplicationContext?

You are creating two different context, so even if bean is singleton it will create single instance per context, 您正在创建两个不同的上下文,因此,即使bean是单例的,它也会为每个上下文创建一个实例,

if you want to cache application context you can create a class and provide singleton instance of application context 如果要缓存应用程序上下文,则可以创建一个类并提供应用程序上下文的单例实例

Autowire the bean. Autowire bean。

By default the spring injects the autowired beans into required classes and these beans are not created an new everytime. 默认情况下,spring会将自动装配的bean注入所需的类中,并且不会每次都创建新的bean。 They are singleton by default. 它们默认为单例。

在bean名称myParametrizedSingletonClass的common.spring.xml文件中,在xml文件中定义bean的同时,将范围单例作为参数添加到其中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM