Default Bean Scope in Spring Framework: Singleton

使用 GPT-4o-mini 回答Java Q&A Hub

問題:

What Is the Default Bean Scope in Spring Framework?

答案:

In the Spring Framework, the default bean scope is singleton. This means that when a bean is defined with the singleton scope, the Spring container will create only one instance of that bean for the entire application context. Every time that bean is requested, the same instance will be returned.

You can define a bean with the singleton scope in various ways, such as using XML configuration or annotations. For example, using annotations, you can define a singleton bean like this:

import org.springframework.stereotype.Component;

@Component
public class MySingletonBean {
    // Bean properties and methods
}

In this case, MySingletonBean will be a singleton by default.

If you need a different scope, such as prototype (where a new instance is created each time the bean is requested), you can specify that explicitly using the @Scope annotation:

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class MyPrototypeBean {
    // Bean properties and methods
}

In summary, the default bean scope in Spring is singleton, but you can change it to other scopes as needed.