在SpringBoot中,可以通過創(chuàng)建一個@ConfigurationProperties
注解的類來自定義配置屬性。以下是一個示例:
@ConfigurationProperties
注解標(biāo)記,同時指定一個前綴來區(qū)分不同配置屬性:import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "custom")
public class CustomProperties {
private String property1;
private int property2;
// 省略getter和setter方法
}
application.properties
或application.yml
中定義自定義配置屬性:custom.property1=value1
custom.property2=123
CustomProperties
類,SpringBoot會自動讀取application.properties
中定義的配置屬性并注入到CustomProperties
實例中:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomController {
@Autowired
private CustomProperties customProperties;
@GetMapping("/properties")
public String getProperties() {
return "Property1: " + customProperties.getProperty1() + ", Property2: " + customProperties.getProperty2();
}
}
這樣,就可以在SpringBoot中自定義配置屬性并使用了。