当我们调用 new Bean() 时会发生什么,其中 Bean 是单例的?

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

您好,这可能是重复的问题,对此感到抱歉,但我找不到 post。

问题 :- 假设有一个 class A 是这样写的

  @Component
  public class A{}

现在当我调用 A a = new A() 两次时,它是否会提供相同的对象? 这可能是个愚蠢的问题,但您能否详细说明一下?

谢谢,

当您在您的示例中调用 A = new A() 时,您将始终获得一个新实例,因为 A 未实现为单例 class。

它被注释为@Component 的事实只会影响 class 当它在 spring 上下文中实例化时,以及使用 = new() 实例化的变量(有例外, 但让我们概括一下) 不在 spring 上下文中。

如果您希望始终拥有相同的 bean,您应该使用 @Autowired 实例化您的变量 "a",方法如下:

@Autowired
private A a;

另请注意,@Autowired 仅在当前 class 也在 spring 上下文中时才有效(您没有使用 =new(...) 实例化它) .

首先,这个是 Singleton class 示例,您不能使用 class 之外的 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;
    } 
}

其次,您可以在 here 中找到很多关于 Bean 的信息,例如您需要使用 @Bean 注释创建 bean。

另外,你可以看看这个post