SpringBoot之讀取配置文件中自定義的值
概念:
一般來說,我們會在配置文件中自定義一些自己需要的值,比如jwt的密匙,或者一些FTP配置等信息
如何獲取:
定義自己需要的屬性

獲取方式一:
使用Spring上下文中的環境獲取


獲取方式二:
使用@Value注解獲取


獲取方式三:
通過@ConfigurationProperties注解獲取,指定前綴,自動映射成對象,@PropertySource可以指定配置文件,使用@ConfigurationProperties注解的前提必須使用@Component注解注釋成一個Bean
package com.springboot.demo.model; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * Component 定義為組件 * ConfigurationProperties 通過前綴+屬性自動注入 * PropertySource 指定配置文件 */ @Component @ConfigurationProperties(prefix = "flower",ignoreUnknownFields = true) @PropertySource(value = { "classpath:application.yml" }) public class Flower { private String name; private String age; public Flower(String name, String age) { this.name = name; this.age = age; } public Flower() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "Flower{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } }


測試:
重啟項目后統一測試
接口一測試結果:

接口二測試結果:

接口三測試結果:

經過測試可以得知三種方法都可以獲取配置文件中的值,其中都是可以組合使用的,比如@ConfigurationProperties+@Value等互相組合
作者:彼岸舞
時間:2021\01\12
內容關於:SpringBoot
本文來源於網絡,只做技術分享,一概不負任何責任
