Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Autowiring inside ApplicationContextInitializer implementation

I have an ApplicationContextInitializer that initializes certain application properties. I am trying to autowire spring's ResourceLoader and a restclient into it, but couldn't. Is it possible to autowire inside an ApplicationContextInitializer implementation?

 @Component
    public class MyApplicationContextInitializer implements
            ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private MyRestClient restClient;

   // some init methods

}

My autowired.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
    default-lazy-init="true">

    <context:property-placeholder/>

    <context:annotation-config />
    <context:component-scan base-package="com.package.containing.classes" />

</beans>
like image 879
aazeem Avatar asked Mar 30 '26 14:03

aazeem


1 Answers

Recently I came across the same pitfall. I was trying to autowire a property inside a ApplicationContextInitializer that didn't work. The symptom was that my application at startup only printed the banner to the console and then silently quit. The reason was that a NullPointerException was raised inside the initialize method since my property was null. While the NPE was a code specific issue in my case it showed that the @Autowire annotation was not processed by Spring because if so Spring should have failed in the initialization due to a missing bean definition matching my property instead of injecting null.

In short: Spring does not perform autowiring to ApplicationContextInitializer.

like image 133
Marc-Christian Schulze Avatar answered Apr 02 '26 08:04

Marc-Christian Schulze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!