主題
- 綁定屬性的方式
- 直接綁定 application.properties 文件中的屬性
- 如何綁定 其他文件中的屬性
1. 綁定屬性的方式
- autowire 注入 Environment bean //獲取屬性的方式,env.getProperties("city.address")
- @Value("${city.address}"") //綁定屬性的方式严望,綁定到某些類上多艇,再使用,用于對屬性分門別類
2. 直接綁定 application.properties 文件中的屬性
pplication.properties 文件中定義
car.field.color=black
car.field.brand=benz
定義 CarProperty 類
- 方法一
@Component //綁定到的property 類首先需要成為一個bean像吻,@Value 實際上是 @BeanPostProcessor 的處理
@Data //添加get/set, intellj lombak插件支持
public class CarProperty {
@Value("${car.field.color}") //直接綁定
private String color;
@Value("#{car.field.brand}")
private String brand;
}
- 方法二
@Component //標(biāo)志為上下文bean, 此處也可不寫墩蔓,但需要在 @EnableConfigurationProperties 指定參數(shù) CarProperty 類
@ConfigurationProperties(prefix = "car.field") //以前綴的形式 將各種屬性 分門別類 與相應(yīng)類 一一對應(yīng)
@Data
public class CarProperty {
private String brand;
private String color;
}
開啟ConfigurationProperties功能
@SpringBootApplication
//開啟configurationProperties,@Value 不需此行注解萧豆,
//@EnableConfigurationProperties(CarProperty.class) //可添加參數(shù),作用是 注入該類bean,此刻無需 @Component 修飾 CarProperty 類
//即昏名,@Component 和 @EnableConfigurationProperties(CarProperty.class)的作用是一樣的涮雷,都是使 CarProperty 成為上下文一個 Bean, 只是注解到到的位置不一樣,取其一即可
public class MainApplication {
public static void main(String[] args){
SpringApplication.run(MainApplication.class, args);
}
}
3. 綁定 car.properties 文件中的屬性
- 前面轻局,默認(rèn)的屬性文件為 application.properties, 現(xiàn)在我們嘗試讀取自定義property 文件
- 達到這種效果洪鸭,必須使用 ConfigurationProperties 這種形式,@Value 夠嗆
- 還有一點注意仑扑,當(dāng)使用 @PropertySource 注解時览爵,盡量使用@Component來生成 bean, 通過 @EnableConfigurationProperties 不起作用
resources 目錄創(chuàng)建car.properties 文件
car.field.color=black
car.field.brand=benz
創(chuàng)建property屬性文件
@Component //此時,務(wù)必使用 @Component
@ConfigurationProperties(prefix = "car.field") //前綴不變
@PropertySource(value="classpath:car.properties") // 限定屬性存在的 屬性文件镇饮,若沒有此注解則為 application.properties 文件,且value 不能為空
@Data
public class CarProperty {
private String brand;
private String color;
}
上述均可通過如下方法驗證
- 創(chuàng)建 CarController
@RestController
@RequestMapping("/car")
@Slf4j
public class CarController {
@Autowired
private CarProperty carProperty;
@RequestMapping(value = "/property", method = RequestMethod.GET)
public String testProperty() {
String name = carProperty.getColor();
log.info("color: " + name);
return "color: " + name;
}
}