HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Boot 2 / Spring Boot – Inject Application Arguments in @Bean and @Compoment

Spring Boot – Inject Application Arguments in @Bean and @Compoment

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

1. ApplicationArguments as constructor injection

This is fairly simple way to gain access to application arguments where we need to use them in constructor itself.

@Component
public class ArgsComponent 
{
	@Autowired
	public ArgsComponent(ApplicationArguments args) 
	{
		//Aceess arguments using args
	}
}

2. ApplicationArguments as autowired dependency

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

@Configuration
public class AppConfiguration 
{
	@Autowired
	private ApplicationArguments args;

	@Bean
	public ArgsComponent argsComponent() {
		
		//access args
		
		return new ArgsComponent();
	}
}

3. Inject Command Line Arguments – Demo

Let’s run a quick demo to understand it’s usage.

In this demo, we are passing two arguments while running the spring boot application from command prompt.

  • —emailClient=Java
  • disableDataService

The first argument (emailClient) is assigned a value. Second argument (disableDataService) is non-option argument. We will access both argument in the application.

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

@Component
public class ArgsComponent 
{
	public ArgsComponent() 
	{
	}
}
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfiguration 
{
	private static final Logger log = LoggerFactory.getLogger(AppConfiguration.class);
	
	@Autowired
	private ApplicationArguments args;

	@Bean
	public AppConfiguration argsComponent() {
		
		verifyArguments();
		
		return new ArgsComponent(args);
	}
	
	public void verifyArguments() 
	{
		//Check is argument is present
		if(args.containsOption("emailClient")) 
		{
			//Get argument values
			List<String> values = args.getOptionValues("emailClient");
			
			log.info("Email clients are :: " + values);
		}
		
		//////////////
			
		List<String> nonOptionArgs = args.getNonOptionArgs();
		
		log.info("Non Option Args List ...");
		
		if (!nonOptionArgs.isEmpty())
		{
			nonOptionArgs.forEach(file -> log.info(file));
		}
	}
}

Start the application and verify output

To Start the application with arguments, run following command from command prompt.

$ java -jar target\SpringBoot2Demo-0.0.1-SNAPSHOT.jar –emailClient=Java disableDataService

Observe the startup logs.

2019-05-06 16:31:36.443  INFO com.howtodoinjava.demo.ArgsComponent     : Email clients are :: [Java]
2019-05-06 16:31:36.443  INFO com.howtodoinjava.demo.ArgsComponent     : Non Option Args List ...
2019-05-06 16:31:36.445  INFO com.howtodoinjava.demo.ArgsComponent     : disableDataService

2019-05-06 16:31:36.461  INFO com.howtodoinjava.demo.AppConfiguration  : Email clients are :: [Java]
2019-05-06 16:31:36.476  INFO com.howtodoinjava.demo.AppConfiguration  : Non Option Args List ...
2019-05-06 16:31:36.477  INFO com.howtodoinjava.demo.AppConfiguration  : disableDataService

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 !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Spring Boot 2 Tutorial

  • Spring Boot – Introduction
  • Spring Boot – Starter parent
  • Spring Boot – Starter templates
  • Spring Boot – Multi-module project
  • Spring Boot – Annotations
  • Spring Boot – Auto configuration
  • Spring Boot – AOP
  • Spring Boot – Logging
  • Spring Boot – DevTools
  • Spring Boot – WAR Packaging
  • Spring Boot – REST API
  • Spring Boot – CRUD
  • Spring Boot – OAuth2
  • Spring Boot – Testing
  • Spring Boot – RestTemplate
  • Spring Boot – Thymeleaf
  • Spring Boot – Hibernate
  • Spring Boot – DataSource
  • Spring Boot – Error Handling
  • Spring Boot – Caching
  • Spring Boot – Retry
  • Spring Boot – BasicAuth
  • Spring Boot – H2 Database
  • Spring Boot – Ehcache 3.x
  • Spring Boot – Gson
  • Spring Boot – RMI
  • Spring Boot – Send Email
  • Spring Boot – Interview Questions

Spring Boot Tutorial

  • Spring Boot – CommandLineRunner
  • Spring Boot – Configure Jetty
  • Spring Boot – Tomcat Default Port
  • Spring Boot – Context Root
  • Spring Boot – SSL [https]
  • Spring Boot – Get all loaded beans
  • Spring Boot – PropertyEditor
  • Spring Boot – @EnableScheduling
  • Spring Boot – Jersey
  • Spring Boot – SOAP Webservice
  • Spring Boot – SOAP Client
  • Spring Boot – JMSTemplate
  • Spring Boot – REST APIs
  • Spring Boot – JSP View
  • Spring Boot – Actuator endpoints
  • Spring Boot – Role Based Security
  • Spring Boot – RSS / ATOM Feed
  • Spring Boot – Ehcache 2.x

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces