Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot: accessing command line args from a bean

I run spring boot application with a single argument - filename. The file contains some properties I need in runtime. When the application starts it checks if args.length==1

But I need this file (properties) in a single point - @Component annotated bean.

Is it a way to get an access to the file's content from it?

like image 403
Buch Avatar asked Apr 05 '18 14:04

Buch


People also ask

What is ApplicationArguments?

public interface ApplicationArguments. Provides access to the arguments that were used to run a SpringApplication .

What does @bean annotation mean?

One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework.


1 Answers

In Spring, there is a bean called ApplicationArguments that provides access to the arguments used to run an application.

@Component
public MyComponent {
    @Autowired
    private ApplicationArguments  applicationArguments;

    public void method() {
        List<String> filenameArgs = applicationArguments.getOptionValues("filename")
    }
}
like image 168
Vaidas Avatar answered Oct 21 '22 09:10

Vaidas