Configuration files are a core component of SpringBoot applications, which determine the behavior, connection parameters, and functional characteristics of the application.
Rational use of SpringBoot's configuration mechanism can not only improve development efficiency, but also enhance application flexibility and maintainability.
1. Multi-environment configuration (Profiles)
SpringBoot supports multi-environment configuration through profiles, which facilitates seamless switching between development, testing and production environments.
Basic usage
Create a configuration file for a specific environment:
• (Development Environment)
• (Test environment)
• (Production Environment)
In the main configuration fileActivate a specific environment in:
spring: profiles: active: dev
Advanced configuration
Use the grouping function (Spring Boot 2.4+) to simplify environment configuration:
spring: profiles: group: dev: local-db, local-cache, dev-api prod: cloud-db, redis-cache, prod-api
Command line activation
No need to modify the configuration file, specify the environment directly at startup:
java -jar --=prod
2. Priority of configuration properties
Understanding the priority order of SpringBoot configurations can help resolve configuration conflicts.
Common configuration source priority (from high to low):
1. Command line parameters
2. Java system properties (())
3. Operating system environment variables
4. Configuration file for a specific profile
5. /yml external to the application
6. /yml inside the application
Application example
For database URL configuration, it can be set at different levels:
# (low priority)spring: datasource: url: jdbc:mysql://localhost:3306/default_db
# Command line parameters (high priority)java -jar --=jdbc:mysql://prod-server:3306/prod_db
The final effect is the URL in the command line parameter.
3. Relaxed Binding
SpringBoot supports multiple attribute naming styles, automatically performs loose binding, and improves configuration flexibility.
Supported naming styles
For Java propertiesserverPort
:
• kebab-case:server-port
(Recommended for .properties and .yml files)
• Hump:serverPort
• Underline:server_port
(Recommended for environment variables)
• Full capital underline:SERVER_PORT
(Standard format of environment variables)
Binding example
Configuration file:
my-app: connection-timeout: 5000 read-timeout: 10000
Java code:
@ConfigurationProperties(prefix = "my-app") public class AppProperties { private int connectionTimeout; private int readTimeout; // getters and setters }
SpringBoot will automaticallyconnection-timeout
Bind toconnectionTimeout
property.
4. Configure random values
In development and testing environments, random values are often needed to be generated, and SpringBoot provides built-in support.
Commonly used random attributes
app: # Random integers random-int: ${} Random integers in range random-int-range: ${[1000,2000]} # Random long integer random-long: ${} # Random string random-string: ${} # Random bytes secret-key: ${[16]}
Application scenarios
Server ports are randomly allocated to avoid port conflicts in development environments:
server: port: ${[8000,9000]}
The test environment uses a random key:
app: security: secret-key: ${}
5. Type-safe configuration properties (@ConfigurationProperties)
use@ConfigurationProperties
Bind structured configuration to provide type safety and automatic code completion.
Basic usage
Configuration class:
@Component @ConfigurationProperties(prefix = "mail") @Validated public class MailProperties { @NotEmpty private String host; @Min(1025) @Max(65536) private int port = 25; @Email private String from; private boolean enabled; // getters and setters }
Configuration file:
mail: host: port: 587 from: noreply@ enabled: true
Collections and complex types
mail: recipients: - admin@ - support@ connection: timeout: 5000 retry: 3 additional-headers: X-Priority: 1 X-Mailer: MyApp
@ConfigurationProperties(prefix = "mail") public class MailProperties { private List<String> recipients = new ArrayList<>(); private Connection connection = new Connection(); private Map<String, String> additionalHeaders = new HashMap<>(); // getters and setters public static class Connection { private int timeout; private int retry; // getters and setters } }
6. Import other configuration files
In large projects, splitting configurations into multiple files can improve maintainability.
Use @PropertySource
@Configuration @PropertySource("classpath:") @PropertySource("classpath:") public class AppConfig { // ... }
use
In Spring Boot 2.4+, you can import other configurations in the main configuration file:
spring: config: import: - classpath: - optional:file:./config/ - configserver:http://config-server:8888/
Noticeoptional:
The prefix indicates that the file does not exist and will not report an error.
7. Encryption and protection of sensitive configurations
In production environments, it is crucial to protect sensitive configurations such as passwords and API keys.
Encryption with Jasypt
1. Add Jasypt dependencies:
<dependency> <groupId></groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.4</version> </dependency>
2. Encryption configuration values:
# Encrypted configuration=ENC(G8Sn36MAJOWJwEgAMZM3Cw0QC9rEEVyn)
3. Provide the decryption key:
java -jar --=mySecretKey
Use environment variables to store sensitive information
spring: datasource: username: ${DB_USERNAME} password: ${DB_PASSWORD}
8. Configure property verification
Verify configuration properties to avoid runtime errors caused by illegal configurations.
Use JSR-303 verification
@ConfigurationProperties(prefix = "") @Validated public class ConnectionProperties { @NotNull @Min(1000) @Max(10000) private Integer timeout; @Pattern(regexp = "^(http|https)://.*$") private String serviceUrl; @Email private String supportEmail; // getters and setters }
Custom verification
@Target({}) @Retention() @Constraint(validatedBy = ) public @interface IpAddress { String message() default "Invalid IP address"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } public class IpAddressValidator implements ConstraintValidator<IpAddress, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return true; } String regex = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; return (regex); } } @ConfigurationProperties(prefix = "") @Validated public class ServerProperties { @IpAddress private String ipAddress; // ... }
9. Use placeholders in configuration
Use placeholders in configuration files to refer to other configuration items for increased flexibility and reduce duplication.
Basic usage
app: name: MyApp api: base-url: version: v1 full-url: ${-url}/${} security: timeout: 3600 timeout-millis: ${}000
default value
Provide default values in case configuration is missing:
app: cache-dir: ${CACHE_DIR:/tmp/cache} max-threads: ${MAX_THREADS:10}
System attributes and environment variable references
server: port: ${PORT:8080} address: ${SERVER_ADDRESS:0.0.0.0} logging: path: ${LOG_PATH:${}/logs}
10. Configure conditional loading
Use Spring's conditional annotations to load configurations based on conditions to improve flexibility.
Use @Profile
@Configuration @Profile("dev") public class DevDatabaseConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } } @Configuration @Profile("prod") public class ProdDatabaseConfig { @Bean public DataSource dataSource() { HikariDataSource dataSource = new HikariDataSource(); ("jdbc:mysql://prod-db:3306/app"); // Other configurations... return dataSource; } }
Use @Conditional
@Configuration @ConditionalOnProperty(name = "", havingValue = "true") public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager(); } } @Configuration @ConditionalOnMissingBean() public class NoCacheConfig { // Alternative configuration}
Based on classpath conditions
@Configuration @ConditionalOnClass(name = "") public class RedisConfig { // Redis related configuration}
11. List and Map Configuration Tips
Effectively represent complex data structures in configuration files.
List in YAML
app: # Simple list servers: - - - # Object List endpoints: - name: users url: /api/users method: GET - name: orders url: /api/orders method: POST
Bind in Java:
@ConfigurationProperties(prefix = "app") public class AppConfig { private List<String> servers = new ArrayList<>(); private List<Endpoint> endpoints = new ArrayList<>(); // getters and setters public static class Endpoint { private String name; private String url; private String method; // getters and setters } }
Map configuration
app: # Simple Mapping feature-flags: enableNewUI: true enableAnalytics: false enableNotifications: true # Complex mapping datasources: main: url: jdbc:mysql://main-db:3306/app username: mainuser maxPoolSize: 20 report: url: jdbc:mysql://report-db:3306/reports username: reportuser maxPoolSize: 5
Bind in Java:
@ConfigurationProperties(prefix = "app") public class AppConfig { private Map<String, Boolean> featureFlags = new HashMap<>(); private Map<String, DataSourceProperties> datasources = new HashMap<>(); // getters and setters public static class DataSourceProperties { private String url; private String username; private int maxPoolSize; // getters and setters } }
12. Configuring metadata using Spring Boot
Create configuration metadata to provide IDE autocomplete and documentation.
Add metadata dependencies
<dependency> <groupId></groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
Add documentation for configuration class
@ConfigurationProperties(prefix = "acme") public class AcmeProperties { /** * Whether to enable ACME service. */ private boolean enabled = false; /** * The remote address of the service. */ @NotEmpty private String remoteAddress; /** * Session timeout, unit in seconds. * The minimum value is 1 minute and the maximum value is 1 hour. */ @Min(60) @Max(3600) private int sessionTimeout = 600; // getters and setters}
Custom metadata
createMETA-INF/
document:
{ "properties": [ { "name": "-key", "type": "", "description": "APISecurity Key,Used for external service authentication。", "sourceType": "" }, { "name": "", "type": "", "description": "Whether to enableAPIRate limit。", "defaultValue": true, "deprecation": { "level": "warning", "replacement": "", "reason": "APIRate limit配置已移动到securityNamespace。" } } ], "hints": [ { "name": "-level", "values": [ { "value": "debug", "description": "Debug log level." }, { "value": "info", "description": "Information log level." }, { "value": "warn", "description": "Warning log level." }, { "value": "error", "description": "Error log level." } ] } ] }
Summarize
In actual development, we should choose the appropriate configuration strategy based on the project size and complexity.
By rationally applying these techniques, we can build more flexible, secure and easy-to-maintain SpringBoot applications, providing solid technical support for rapid changes in business needs.
This is the article shared about the practical skills of 12 SpringBoot configuration files. For more information about practical skills of SpringBoot configuration files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!