Sobes.tech
Middle

How to create a singleton bean when launching a Spring application?

sobes.tech AI

Answer from AI

To create a singleton bean when starting a Spring application, several approaches can be used:

  1. Using the @Component annotation (or its derivatives @Service, @Repository, @Controller) and specifying scope="singleton" (although this is the default value). Spring by default creates these beans eagerly (at context startup).

    // Example of a singleton class
    @Component
    public class MySingletonBean {
        // Fields and methods of the class
    }
    
  2. Using the @Bean annotation inside a @Configuration class. By default, beans declared this way are also singletons and are created at startup.

    // Example of a configuration class
    @Configuration
    public class AppConfig {
    
        @Bean
        public MySingletonBean mySingletonBean() {
            return new MySingletonBean();
        }
    }
    
  3. Explicitly specify lazy-init="false" for XML configuration or @Lazy(false) for Java configuration. This guarantees the bean is created not on the first request, but at context startup, even if its scope is not singleton. However, for scope singleton, this behavior is the default.

    // Example with @Lazy(false)
    @Component
    @Lazy(false)
    public class AnotherSingletonBean {
        // Fields and methods of the class
    }
    
    // Example of XML configuration
    // <bean id="myXmlSingletonBean" class="com.example.MySingletonBean" lazy-init="false"/>
    

For all the methods listed above, unless otherwise specified, Spring creates a single instance of the bean and places it in the ApplicationContext during its initialization. This instance is then used for all dependencies.