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:
-
Using the
@Componentannotation (or its derivatives@Service,@Repository,@Controller) and specifyingscope="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 } -
Using the
@Beanannotation inside a@Configurationclass. 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(); } } -
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 notsingleton. However, for scopesingleton, 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.