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.