Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get command line argument inside BeanFactoryPostProcessor?

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?

like image 310
Oleksandr Papchenko Avatar asked Jan 15 '19 14:01

Oleksandr Papchenko


2 Answers

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;
    }

}
like image 171
Ken Chan Avatar answered Nov 16 '22 15:11

Ken Chan


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)
like image 28
Abdelghani Roussi Avatar answered Nov 16 '22 17:11

Abdelghani Roussi