简体   繁体   English

在春季参考单例豆

[英]Reference to singleton bean in Spring

I'm new to Spring and thus apologies in advance if the questions seems to be trivial. 我是Spring的新手,因此如果问题看起来很琐碎,请提前道歉。

When I declare a bean in spring it is singleton by default. 当我在春天声明一个bean时,默认情况下它是单例的。 When spring initializes beans from config.xml it's using default creator. 当spring从config.xml初始化bean时,它使用的是默认创建器。 If I declare my private creator and getInstance method for a class, I don't get reference to the bean created during Spring initialization - I simply create same class again and this class is referenced when getInstance() is called any time later. 如果我声明一个类的私有创建者和getInstance方法,则不会引用在Spring初始化期间创建的Bean-我只是再次创建相同的类,并且在以后任何时候调用getInstance()时都引用该类。

My question is how can I get reference to the singleton created during initialization (to the bean defined in config.xml) from code. 我的问题是如何从代码中获取初始化期间创建的单例(对config.xml中定义的Bean)的引用。

If you have a factory method in your code, then make xml configuration call that factory method instead of a constructor. 如果您的代码中有一个工厂方法,则使xml配置调用该工厂方法而不是构造函数。 DO NOT call getInstance from your Java code. 不要从您的Java代码中调用getInstance

<bean id="fromFactory" class="org.example.MyFactory" factory-method="getInstance" />

Spring will create a single instance of your class by default. Spring默认会创建您的类的单个实例。 It will call the class's constructor once. 它将一次调用该类的构造函数。 I think you have confused this with the 我认为您已经将此与

public static void getInstance() 

idiom for singletons in Java which is an attempt to enforce in your class that you can never have more than one instance. Java中单例的惯用语,这是在您的类中强制实施的尝试,即您永远不能有多个实例。

Spring has constructed a single instance of your class and is storing it in the Spring container ready for you to use. Spring已经构造了您的类的单个实例,并将其存储在Spring容器中供您使用。 To get a reference to the instance Spring has created, you need to retrieve it from Spring's application context. 要获得对Spring创建的实例的引用,您需要从Spring的应用程序上下文中检索它。

I think this could be relevant to your question: Why is Spring's ApplicationContext.getBean considered bad? 我认为这可能与您的问题有关: 为什么Spring的ApplicationContext.getBean被认为是错误的?

There's a number of ways: you can get your bean instance from ApplicationContext, you can @Autowire it, etc. 有很多方法:可以从ApplicationContext获取bean实例,可以@Autowire等等。

If your class implements the Singleton Pattern then there is no way getInstance() will return an instance other then what Spring has created. 如果您的类实现了Singleton Pattern,getInstance()将无法返回除Spring创建的实例之外的其他实例。

how can I get reference to the singleton created during initialization 我如何获得在初始化期间创建的单例的引用

Basically, you should have it injected to the other class, where you will need it. 基本上,应该将它注入需要的其他类中。 And you can also refer to it by ApplicationContext.getBean() , although it is not that elegant . 您也可以通过ApplicationContext.getBean()引用它,尽管它并不那么优雅

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

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