Spring Boot has a quite sophisticated environment variable and config properties management.
Using the @Value Annotation
In general terms, you can pass arguments with -DargumentName . For example:
-DargumentName="value1"
Then in your Spring Boot application, you can retrieve the value by doing:
@Value("${argumentName}") private String myVariable
Using the @Component Bean
But you can do it also in a more sophisticated way, using the @Component Bean as in the following example:
@Component
class SampleComponent {
private static final Logger log = LoggerFactory.getLogger(SampleComponent.class);
@Autowired
public SampleComponent(ApplicationArguments args) {
boolean option = args.containsOption("myoption");
if (option) log.info("You have included myoption!");
List<String> _args = args.getNonOptionArgs();
log.info("Extra args ...");
if (!_args.isEmpty()) _args.forEach(file -> log.info(file));
}
}
When you execute args.containsOption(“myoption”) , it will expect the argument as follows:
$ ./mvnw spring-boot:run -Drun.arguments="--myoption"
Another possible way to pass the arguments is also like this :
$ ./mvnw spring-boot:run -Drun.arguments="arg1,arg2"
Using Spring Boot’s Environment class
Another option is to use the org.springframework.core.env.Environment to retrieve the argument. Example:
java -jar app.jar --myproperty=123
in application call:
import org.springframework.core.env.Environment;
@Autowired private Environment env;
String someProperty = env.getProperty("myproperty");
Found the article helpful? if so please follow us on Socials