Accessing Command-Line Application Arguments in Spring Boot

Learn to retrieve and access the application startup arguments in @Component annotated classes and @Bean annotated methods in a Spring boot application using org.springframework.boot.ApplicationArguments class.

For Spring Boot 2.x, we can pass the arguments using -Dspring-boot.run.arguments:

mvn spring-boot:run -Dspring-boot.run.arguments=--customArgument=custom

Each word after the run command is an argument. The arguments that start with '-' are option argument; and others are non-option arguments.

1. Spring ApplicationArguments as Constructor Injection

The constructor injection is a fairly simple way to gain access to application arguments. Here we need to use the command line arguments in the constructor itself.


@Component
public class ArgsComponent
{
	private List<String> customArgument;

	@Autowired
	public ArgsComponent(ApplicationArguments args)
	{
		this.customArgument = args.getOptionValues("customArgument");
	}
}

2. @Autowired ApplicationArguments

If we do not specifically require arguments in the constructor, autowiring is the cleaner way to inject ApplicationArguments class in any Spring component or configuration class.

@Component
public class ArgsComponent
{
	private List<String> customArgument;

	@Autowired
	private ApplicationArguments args;


	public ArgsComponent()
	{
		this.customArgument = args.getOptionValues("customArgument");
	}
}

3. Using @Value Annotation

The @Value annotation is generally used to inject the values configured in the application.properties. We can use @Value in inject the command line arguments as well.

It also means that command-line arguments can override the application properties.

@Component
public class ArgsComponent
{
	@Value("${customArgument}")
	private String customArgument;

	//...
}

Drop me your questions related to this spring boot command line arguments example to demonstrate access command line arguments while executing spring boot jar application.

Happy Learning !!

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.