76

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?

2
  • Look at this post stackoverflow.com/questions/3187899/…
    – Vishal
    Oct 23, 2011 at 18:55
  • You may want to include log4j.properties anyways, at least for Spring startup - until Spring has initialized your logging bean, it will use whatever the defaults are for its internal logging, and typically, if you're using Log4J, that will be the log4j.properties file defined on the classpath. This file doesn't have to be very complex - typically it can simply output to the console because if the app successfully starts up, the meaningful logging will be through your custom bean. Oct 24, 2011 at 0:35

5 Answers 5

56

Your options are:

  1. Use @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 factory
  2. Make the factory an actual factory for loggers, and inject the loggers into the beans instead of calling the factory directly – this is essentially the same as option 1, except the dependency is implied. This is the option I'd recommend.
  3. Move the initialisation code to a part of your code where call order is specified – the main() 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.

7
  • I was kind of implementing the third option but that means I initialise logger first explicitly outside of spring. My preference was have majority of objects life cycle be managed by spring but I understand your point that a good design pattern should be able to take care of it.
    – Prasanna
    Oct 24, 2011 at 4:48
  • @Prasanna If you want most of your objects to be managed by Spring, you should definitely either manage the loggers in Spring as well, or encapsulate logger creation in your logger factory and inject that into your other classes. If you want to support retrieving loggers using the LogManager static methods, then you'll have to use option 3 though – since LogManager is a (specialized) object factory that cannot be reasonably managed by Spring.
    – millimoose
    Oct 24, 2011 at 11:49
  • @Inerida, yes, LogManager is the problem and I do not see any other option other than 3,
    – Prasanna
    Oct 24, 2011 at 15:51
  • I use @DependsOn({"anotherBean"}) docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
    – prayagupa
    Feb 27, 2018 at 18:40
  • 1
    @prayagupd - you’re a hero to us all and SO is better for your efforts. You didn’t need my permission anyway and I figured asking would reduce the risk of forgetting about it by the time I’d gotten home
    – millimoose
    Feb 28, 2018 at 12:26
19

You can @Autowired an @Configuration in the main @Configuration

@Configuration
@Import(BusinessConfig.class, EarlyBeans.class)
public class MainConfiguration {

    // The bean defined in EarlyBean will be loaded before 
    // most beans references by MainConfiguration, 
    // including those coming from BusinessConfig
    @Autowired
    EarlyBeans earlyBeans;

}

@Configuration
public class EarlyBeans {
    @Bean
    public Void earlyBean(ApplicationContext appContext) {
        // .getBeansOfType allows to call for beans which might not exist
        appContext.getBeansOfType(TechnicalBean.class);

        return null;
    }

}
5
  • Very useful, just 1 comment - one of @Import(EarlyBeans.class) or @Autowired EarlyBeans earlyBeans; is enough to make it work.
    – Tomas F.
    Feb 1, 2017 at 10:20
  • 3
    Sorry for commenting on an old question - how is this any different from calling appContext.getBeansOfType(TechnicalBean.class) OR using @Autowired TechnicalBean inside the MainConfiguration itself? Jan 14, 2018 at 6:42
  • This scales very terribly. Mar 3 at 15:43
  • > how is this any different from calling appContext.getBeansOfType(TechnicalBean.class) OR using @Autowired TechnicalBean inside the MainConfiguration itself? 10 years later, I would say I've done it this way for separate of concerns. But it seems equivalent.
    – blacelle
    Mar 4 at 18:42
  • @MehdiCharife As of 2024, you can reach similar behavior with AutoConfigurations. In some cases, I also went with BeanPostProcessor which are beans instantiated earlier than later.
    – blacelle
    Mar 4 at 18:44
4

This is a feature requested but not resolved. You can use depends-on but is too verbose. Follow tis link for more information: https://jira.springsource.org/browse/SPR-3948

1
  • The link is dead. It's been 12 years now. Is there a solution now? Mar 3 at 15:29
1

You can split your application context as multiple and use import in main application context. You can put the main environment settings first in the order of import and then continue adding other files.

It could be like below.

<!-- Import environment properties settings. -->
<import resource="Spring-Env.xml"/>
<!-- Import All the other Application contexts. -->
<import resource="Spring-MainApplicationContext.xml"/>
0

in addition to the mentioned points, you can use SpringApplicationRunListener interface for config different application life cycles. you can config ConfigurableBootstrapContext in starting, environmentPrepared phases furthermore you can config ConfigurableApplicationContext in contextPrepared, contextLoaded, started, ready, failed phases.

for your case:

Called once the ApplicationContext has been created and prepared, but before sources have been loaded.

default void contextPrepared(ConfigurableApplicationContext context) { }

        public class AppConfiguration implements SpringApplicationRunListener {
    
        public void contextPrepared(ConfigurableApplicationContext context) {
            var provider = new ClassPathScanningCandidateComponentProvider(false) {
                @Override
                protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
                    return super.isCandidateComponent(beanDefinition) || beanDefinition.getMetadata().isAbstract();
                }
            };
            // you are gonna find specific class such as the classes marked by Qualifier
            provider.addIncludeFilter(new AnnotationTypeFilter(Qualifier.class, true, true));
    
            final Set<BeanDefinition> classes = provider.findCandidateComponents("com.tosan");
            classes.forEach(beanDefinition -> {
                try {
                    //add bean to context
context.getBeanFactory().registerSingleton(Objects.requireNonNull(beanDefinition.getBeanClassName()), new YourBeens());
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

Don't forget to put the listener in src/main/resources/META-INF/spring.factories like below otherwise the listener will not run.

org.springframework.boot.SpringApplicationRunListener=com.example.AppConfiguration
1
  • Your answer is incomprehensible. Mar 3 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.