Sobes.tech
Junior — Middle

How to implement the Singleton pattern using Spring Framework capabilities?

sobes.tech AI

Answer from AI

In Spring Framework, the Singleton pattern is implemented by default for beans. This means that if you declare a component using annotations like @Component, @Service, @Repository, or through XML configuration, Spring will create a single instance of that bean and use it everywhere it is required.

Example:

@Service
public class MySingletonService {
    public void doSomething() {
        System.out.println("Singleton service is working");
    }
}

When injecting this service into other components via @Autowired, you will always get the same instance.

If you want to explicitly specify the scope, you can use the @Scope("singleton") annotation, but this is not necessary as singleton is the default scope.

Thus, Spring manages the lifecycle and guarantees that the bean will be a singleton within the application context.