I have a library doing runtime setup and configuration of log4j (no log4j.properties or log4j.xml). I have defined a bean with class called MyLoggerFactory and I want this to be the first bean to be initialised using spring. I have seen that an issue has already been filed with spring to have support for order of initialisation but I was wondering whether there was a way to mark a bean as the first bean to be initialised by spring container?
The @DependsOn annotation in spring forces the IoC container to initialize one or more beans. This annotation is directly used on any class or indirectly annotated with @Component or on methods annotated with @Bean .
In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation.
Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.
Your options are:
@DependsOn
annotation(available after spring 3.0.x) or depends-on
xml-attribute and make all classes that use the configured loggers depend on the logger factorymain()
method, or a ServletContextListener
registered before the one that initializes Spring.There is no way to explicitly define initialisation order in Spring and likely never will be – there's no way to define useful semantics for it considering you can load many application context configuration files which might have conflicting orderings. I've yet to see a case where the desired ordering couldn't be achieved by refactoring your code to better conform to the dependency injection pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With