Skip to content

Autowired property is null in EnvironmentPostProcessor implementation class on startup

In my SpringBoot app, I have Autowired an configObject in the class that implements EnvironmentPostProcessor.

The injected class reads data from a different source on startup as this is required for the app to work.

But upon starting the application, the configObject is coming off as Null.

@SpringBootApplication
@EnableEncryptableProperties
@EnableConfigurationProperties
@EnableCaching
@Slf4j
public class SBApplication {
    public static void main(String[] args) {
        SpringApplication.run(SBApplication.class, args);
    }
}

And the AppEnvironmentPostProcessor class where the Autowired object is called. This class is configured as org.springframework.boot.env.EnvironmentPostProcessor in spring.factories. The class gets called on start up.

@Slf4j
public class AppEnvironmentPostProcessor implements
        EnvironmentPostProcessor, Ordered {

    @Autowired
    KeysConfig keysConfig;

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment,
                                       SpringApplication application) {
        // keysConfig is null
        String key = keysConfig.getSecretKeyMap().get("key12");
    }
}

And in the KeysConfig class

@Component
public final class KeysConfig {
    public Map getSecretKeyMap() {
        //Returns key map
    }
}

I am using Intellij Ultimate. How can I debug and resolve this?

Answer

EnvironmentPostProcessors are created before the application context has been created and, therefore, before dependency injection is possible. This means that @Autowired won’t work.

You’ll have to update your implementation to create an instance of KeysConfig itself, or to use a different approach that mimics whatever KeysConfig currently does.