Spring Boot 自定义配置类实现步骤及示例
步骤说明
- 创建配置类 :定义一个 POJO 类,使用
@ConfigurationProperties
注解指定配置前缀。 - 启用配置绑定 :在启动类或配置类上添加
@EnableConfigurationProperties
注解。 - 配置文件写法 :在
application.properties
或application.yml
中按前缀配置参数。 - 注入配置类 :通过
@Autowired
在需要的组件中使用配置参数。
完整代码示例
java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "app.config") // 指定配置前缀
@Data // Lombok 自动生成 getter/setter
public class AppConfig {
// 基本类型
private String name; // 字符串类型
private int port; // 整型
private boolean enabled; // 布尔型
private double version; // 双精度浮点型
// 集合类型
private List<String> roles; // 列表
private Map<String, String> metadata; // 键值对
// 嵌套对象
private NestedConfig nested;
// 嵌套类(需在父类中定义或单独定义)
@Data
public static class NestedConfig {
private String field1;
private Integer field2;
}
}
启用配置绑定
在 Spring Boot 启动类或配置类上添加 @EnableConfigurationProperties
:
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(AppConfig.class) // 启用配置类
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配置文件示例
application.properties
properties
app.config.name=MyApp
app.config.port=8080
app.config.enabled=true
app.config.version=1.0.0
app.config.roles=ROLE_USER,ROLE_ADMIN
app.config.metadata.key1=value1
app.config.metadata.key2=value2
app.config.nested.field1=nestValue
app.config.nested.field2=42
application.yml
yaml
app:
config:
name: MyApp
port: 8080
enabled: true
version: 1.0.0
roles:
- ROLE_USER
- ROLE_ADMIN
metadata:
key1: value1
key2: value2
nested:
field1: nestValue
field2: 42
字段类型总结表格
字段类型 | 字段名 | 配置示例 | 说明 |
---|---|---|---|
String | name |
app.config.name=MyApp |
基础字符串配置 |
int | port |
app.config.port=8080 |
整数类型配置 |
boolean | enabled |
app.config.enabled=true |
布尔值开关配置 |
double | version |
app.config.version=1.0.0 |
浮点数配置 |
List | roles |
app.config.roles=ROLE_USER,ROLE_ADMIN |
列表集合配置(逗号分隔) |
Map | metadata |
app.config.metadata.key1=value1 |
键值对配置(YAML 需层级结构) |
嵌套对象 | nested |
app.config.nested.field1=nestValue |
嵌套对象需通过子属性层级配置 |
关键注释说明
@ConfigurationProperties
:必须指定prefix
属性,对应配置文件的前缀。- 嵌套对象 :通过字段名继续扩展配置层级(如
nested.field1
)。 - 集合类型 :
List
用逗号分隔值,Map
需通过键名直接赋值。 - 启用配置 :通过
@EnableConfigurationProperties
或在配置类上添加@Component
自动注册 Bean。