Spring Boot 自定义配置类实现步骤及示例
步骤说明
- 创建配置类:定义一个 POJO 类,使用
@ConfigurationProperties
注解指定配置前缀。 - 启用配置绑定:在启动类或配置类上添加
@EnableConfigurationProperties
注解。 - 配置文件写法:在
application.properties
或application.yml
中按前缀配置参数。 - 注入配置类:通过
@Autowired
在需要的组件中使用配置参数。
完整代码示例
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;// 嵌套类(需在父类中定义或单独定义)@Datapublic static class NestedConfig {private String field1;private Integer field2;}
}
启用配置绑定
在 Spring Boot 启动类或配置类上添加 @EnableConfigurationProperties
:
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
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
app:config:name: MyAppport: 8080enabled: trueversion: 1.0.0roles:- ROLE_USER- ROLE_ADMINmetadata:key1: value1key2: value2nested:field1: nestValuefield2: 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。