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。