Passing an arguments in springboot
In Spring Boot, there are several ways to pass arguments or parameters into your application or methods. Here are some common approaches:
1. Application Arguments (Command-Line Arguments)
Spring Boot applications can accept arguments passed from the command line, which can be accessed in the application using ApplicationArguments
:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class MyAppRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
if (args.containsOption("myArg")) {
System.out.println("Argument passed: " + args.getOptionValues("myArg"));
}
}
}
Run the application with:
java -jar myapp.jar --myArg=value
2. Environment Variables
Spring Boot can read environment variables directly, which can be accessed using @Value
or the Environment
object:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Value("${MY_ENV_VAR}")
private String myEnvVar;
@GetMapping("/env")
public String getEnvVar() {
return "Env Variable: " + myEnvVar;
}
}
Set the environment variable and run the application:
export MY_ENV_VAR=value
java -jar myapp.jar
3. Application Properties
my.config.value=HelloSpringBoot
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Value("${my.config.value}")
private String configValue;
@GetMapping("/config")
public String getConfigValue() {
return "Config Value: " + configValue;
}
}
4. Path Variables and Request Parameters in REST Controllers
When working with REST endpoints, arguments can be passed as path variables or request parameters:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/path/{id}")
public String getPathVariable(@PathVariable String id) {
return "Path Variable: " + id;
}
@GetMapping("/param")
public String getRequestParam(@RequestParam String name) {
return "Request Parameter: " + name;
}
}
- Path Variable:
http://localhost:8080/path/123
- Request Parameter:
http://localhost:8080/param?name=SpringBoot
In Spring Boot, @EnableConfigurationProperties
is used to bind external configuration properties (from sources like application.properties
, application.yml
, or environment variables) to a strongly typed Java object. This approach is particularly useful when you have multiple configuration properties that are related, allowing you to centralize and organize them into a single configuration class.
Here’s how to use @EnableConfigurationProperties
in a Spring Boot application:
Step-by-Step Guide
1. Create a Configuration Properties Class
First, define a class to represent the configuration properties. Use @ConfigurationProperties
to specify the prefix for properties that should be mapped to fields in this class.
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private int timeout;
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
In this example, properties with the prefix myapp
will be mapped to the fields in MyAppProperties
.
2. Enable Configuration Properties
In your main application class or any configuration class, use @EnableConfigurationProperties
to enable the binding of properties to the configuration class.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(MyAppProperties.class)
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
}
3. Define Properties in application.properties
or application.yml
Next, define the actual values for these properties in your application.properties
or application.yml
file:
# application.properties
myapp.name=SpringBootApp
myapp.timeout=5000
Or in application.yml
:
# application.yml
myapp:
name: SpringBootApp
timeout: 5000
4. Access the Configuration Properties
You can inject the MyAppProperties
class wherever you need to access these properties:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private final MyAppProperties myAppProperties;
public MyController(MyAppProperties myAppProperties) {
this.myAppProperties = myAppProperties;
}
@GetMapping("/config")
public String getConfig() {
return "App Name: " + myAppProperties.getName() + ", Timeout: " + myAppProperties.getTimeout();
}
}
Benefits of Using @EnableConfigurationProperties
- Type Safety: By binding properties to a POJO, you get type safety, so properties will be checked at startup.
- Organization: Group related properties together in a single class for better maintainability.
- Validation: You can use
@Validated
and validation annotations like@NotNull
or@Min
on fields to enforce rules on the configuration values.
Example with Validation
To add validation, simply annotate the configuration properties class with @Validated
and use constraints:
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@ConfigurationProperties(prefix = "myapp")
@Validated
public class MyAppProperties {
@NotNull
private String name;
@Min(1000)
private int timeout;
// Getters and Setters
}
If any of the properties don’t meet these constraints, the application will fail to start, providing feedback on invalid configuration.
Override properties value via command line arguments
- java -jar myapp.jar --myapp.name="override-name"
- java -jar myapp.jar --spring.profile.active="prod"