Defining External Configuration
Configuration values can be defined in the application.yml file to externalize settings from the application logic.
server:
port: 9000
servlet:
context-path: /api
app:
config:
service-name: "user-auth-service"
build-version: 2.5.1
Method 1: Using the @Value Annotation
The @Value annotation allows for direct injection of property values into fields. This approach is suitable for simple use cases where only a few distinct properties are needed.
Controller Implementation
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/config")
public class ValueInjectionController {
@Value("${app.config.service-name}")
private String serviceName;
@Value("${app.config.build-version}")
private String appVersion;
@GetMapping("/value")
public void fetchViaValue() {
log.info("Service: {}, Version: {}", serviceName, appVersion);
}
}
Method 2: Type-safe Configuration with @ConfigurationProperties
For grouping related configurations, creating a dedicated configuration class using @ConfigurationProperties is recommended. This method provides type safety and better organization for complex data structures.
Configuration Properties Class
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;
@Data
@Component
@ConfigurationProperties(prefix = "app.config")
public class AppConfigProperties {
private String serviceName;
private String buildVersion;
}
Controller Implementation
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/properties")
public class PropertiesInjectionController {
private final AppConfigProperties appConfigProperties;
@Autowired
public PropertiesInjectionController(AppConfigProperties appConfigProperties) {
this.appConfigProperties = appConfigProperties;
}
@GetMapping("/bean")
public void fetchViaPropertiesBean() {
log.info("Retrieved Config - Name: {}, Ver: {}",
appConfigProperties.getServiceName(),
appConfigProperties.getBuildVersion());
}
}