淺談SpringBoot主流讀取配置檔案三種方式
阿新 • • 發佈:2020-09-19
讀取配置SpringBoot配置檔案三種方式
一、利用Bean註解中的Value(${})註解
@Data @Component public class ApplicationProperty { @Value("${application.name}") private String name; }
該方式可以自動讀取當前配置檔案appliation.yml 或者application.properties中的配置值
區別在於讀取yml檔案時候支援中文編碼,peoperties需要轉碼
二、利用@ConfigurationProperties(prefix = "developer")註解
@Data @ConfigurationProperties(prefix = "developer") @Component public class DeveloperProperty { private String name; private String website; private String qq; private String phoneNumber; }
該方式直接將當前載入yml配置檔案字首為developer的屬性
讀取developer.name...
pom檔案中引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
三、前兩種讀取配置的使用方式
//使用方法 private final ApplicationProperty applicationProperty; private final DeveloperProperty developerProperty; @Autowired public PropertyController(ApplicationProperty applicationProperty,DeveloperProperty developerProperty) { this.applicationProperty = applicationProperty; this.developerProperty = developerProperty; } @GetMapping("/property") public Dict index() { System.out.println("name:"+applicationProperty.getName()); System.out.println("version:"+applicationProperty.getVersion()); System.out.println("DevName:"+applicationProperty.getDeveloperName()); }
四、用Hutool的方式讀取配置檔案(不支援yml格式)
1.用Props的方式讀取
static Props props1 = new Props("application.properties",CharsetUtil.CHARSET_UTF_8);
2.用Setting的方法讀取
static Setting setting = new Setting("application-dev.yml",CharsetUtil.CHARSET_UTF_8,true);
3.將配置檔案讀取
public class Constant { static Props props1 = new Props("application.properties",CharsetUtil.CHARSET_UTF_8); static Setting setting = new Setting("application-dev.properties",true); public static final String Name ; public static final String SettingName ; static { Name = props.getStr("application.name"); SettingName = setting.getByGroup("name","application"); } }
4.使用方式
System.out.println(Constant.DevName+"------"+Constant.DevWebsite);
直接用常量類呼叫該類屬性即可使用
到此這篇關於淺談SpringBoot主流讀取配置檔案三種方式的文章就介紹到這了,更多相關SpringBoot主流讀取配置內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!