簡體   English   中英

當我們調用Bean為單例的new Bean()時會發生什么?

[英]What happen when we call new Bean() where Bean is singleton?

嗨,所有這可以是重復的問題,對此感到抱歉,但是我找不到那個帖子。

問題:-假設已經以這種方式編寫了A類

  @Component
  public class A{}

現在,當我兩次調用A a = new A()時,是否會提供相同的對象? 這可能是愚蠢的問題,但是您能否詳細說明一下?

謝謝,

在示例中,當您調用A = new A()時,總是會得到一個新實例,因為A沒有實現為單例類。

注解為@Component的事實僅會在該類在Spring上下文中實例化時影響該類,而用= new()實例化的變量(有例外,但讓我們概括)不會在Spring上下文中影響該類。

如果您希望始終擁有相同的bean,則應通過以下方式使用@Autowired實例化變量“ a”:

@Autowired
private A a;

還要注意,@Autowired僅在當前類也在spring上下文中時才起作用(您未使用= new(...)實例化它)。

首先,這是Singleton類示例,您不能從類外部使用new關鍵字實例化它,因為您的構造函數是私有的。

 class MySingleton
{
    static MySingleton instance = null;
    public int x = 10;

    // private constructor can't be accessed outside the class
    private MySingleton() {  }

    // Factory method to provide the users with instances
    static public MySingleton getInstance()
    {
        if (instance == null)        
             instance = new MySingleton();

        return instance;
    } 
}

其次,您可以在此處找到許多有關Bean的信息,例如,您需要使用@Bean注釋創建Bean。

此外,您可以看一下這篇文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM