<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
此處理器能在編譯期生成 `META-INF/spring-configuration-metadata.json`,提供 IDE 智能提示與配置校驗。
myProps:
simpleProp: simplePropValue
arrayProps: 1,2,3,4,5
listProp1:
- name: abc
value: abcValue
- name: efg
value: efgValue
listProp2:
- config2Value1
- config2Vavlue2
mapProps:
key1: value1
key2: value2
@Component
@ConfigurationProperties(prefix = "myProps")
public class MyProps {
private String simpleProp;
private String[] arrayProps;
private List<Map<String, String>> listProp1 = new ArrayList<>();
private List<String> listProp2 = new ArrayList<>();
private Map<String, String> mapProps = new HashMap<>();
// String 必須有 setter;集合/陣列/Map 僅需 getter(Spring 會實例化後填充)
public String getSimpleProp() { return simpleProp; }
public void setSimpleProp(String simpleProp) { this.simpleProp = simpleProp; }
public String[] getArrayProps() { return arrayProps; }
public void setArrayProps(String[] arrayProps) { this.arrayProps = arrayProps; }
public List<Map<String, String>> getListProp1() { return listProp1; }
public List<String> getListProp2() { return listProp2; }
public Map<String, String> getMapProps() { return mapProps; }
public void setMapProps(Map<String, String> mapProps) { this.mapProps = mapProps; }
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConfigTest {
@Autowired private MyProps myProps;
@Autowired private ObjectMapper objectMapper;
@Test
public void propsTest() throws JsonProcessingException {
System.out.println("simpleProp: " + myProps.getSimpleProp());
System.out.println("arrayProps: " + objectMapper.writeValueAsString(myProps.getArrayProps()));
System.out.println("listProp1: " + objectMapper.writeValueAsString(myProps.getListProp1()));
System.out.println("listProp2: " + objectMapper.writeValueAsString(myProps.getListProp2()));
System.out.println("mapProps: " + objectMapper.writeValueAsString(myProps.getMapProps()));
}
}
simpleProp: simplePropValue
arrayProps: ["1","2","3","4","5"]
listProp1: [{"name":"abc","value":"abcValue"},{"name":"efg","value":"efgValue"}]
listProp2: ["config2Value1","config2Vavlue2"]
mapProps: {"key1":"value1","key2":"value2"}
| 類型 | YAML 寫法 | Java 欄位 | Setter 需求 |
|---|---|---|---|
| 純量 | key: value | String/Integer 等 | 必須 |
| 陣列 | key: 1,2,3 | String[] / List | 選填 |
| 列表-物件 | key: [{a:1},{a:2}] | List<Map> / List<POJO> | 不需 |
| 列表-純量 | key: [v1, v2] | List<String> | 不需 |
| Map | key: {k1:v1, k2:v2} | Map<String, String> | 選填 |
掌握 `@ConfigurationProperties`,告別散落在程式碼中的 `@Value("${...}")`,擁抱型別安全、結構化、可驗證的配置管理方式。