Junior — Middle
Can you explain how singleton beans are implemented in applications?
sobes.tech AI
Answer from AI
A singleton bean in a Java application is an object that is created as a single instance and used throughout the application. In the Spring Framework, for example, all beans are singleton by default.
The implementation of a singleton bean usually involves:
- Marking the class with the
@Componentannotation or declaring it as a bean in the configuration. - The Spring container creates one instance of this class at application startup.
- When requesting the bean from the context, the same object is always returned.
Example:
import org.springframework.stereotype.Component;
@Component
public class MySingletonBean {
// fields and methods
}
Usage:
@Autowired
private MySingletonBean mySingletonBean;
mySingletonBean will refer to the same object throughout the application.
If you create a singleton manually without Spring, you can use the Singleton pattern with a private constructor and a static method to get the instance.