I am using Spring boot for my application written on Kotlin. I am able to get command line arguments using Environment.getProperty("nonOptionArgs", Array<String>::class.java)
However, inside BeanFactoryPostProcessor
i cannot autowire environment - as this post-processor is running too early in the lifecycle. How I can access command line arguments inside BeanFactoryPostProcessor
?
Well , you can implement your BeanFactoryPostProcessor
with EnvironmentAware
to get the Environment
:
@Component
public class FooBeanFactoryPostProcessor implements BeanFactoryPostProcessor , EnvironmentAware{
private Environment env;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
env.getProperty("nonOptionArgs");
//I should be able to access env at here .Hehe
}
@Override
public void setEnvironment(Environment environment) {
this.env = environment;
}
}
From your comment :
I would like to define dynamically beans based on command argument values. Why to i do this in BeanFactoryPostProcessor - is to be sure that bean definitions are there before actual bean instantiation- so i don't need @DependsOn annotation.
In term of loading beans conditionally (like auto-configuration in spring boot), I would say that it's much cleaner to use the @ConditionalXXX annotations, most specifically the @ConditionalOnProperty.
Referencing the Java-doc for @ConditionalOnProperty
here they said :
Conditional that checks if the specified properties have a specific value. By default the properties must be present in the Environment and not equal to false. The havingValue() and matchIfMissing() attributes allow further customizations.
So you can do something similar to :
@ConditionalOnProperty(prefix = "my.env", name = "var", havingValue = "true", matchIfMissing = false)
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