浅谈SpringBoot主流读取配置文件三种方式
读取配置SpringBoot配置文件三种方式
一、利用Bean注解中的Value(${})注解
@Data
@Component
publicclassApplicationProperty{
@Value("${application.name}")
privateStringname;
}
该方式可以自动读取当前配置文件appliation.yml 或者application.properties中的配置值
区别在于读取yml文件时候支持中文编码,peoperties需要转码
二、利用@ConfigurationProperties(prefix="developer")注解
@Data
@ConfigurationProperties(prefix="developer")
@Component
publicclassDeveloperProperty{
privateStringname;
privateStringwebsite;
privateStringqq;
privateStringphoneNumber;
}
该方式直接将当前加载yml配置文件前缀为developer的属性
读取developer.name...
pom文件中引入依赖
org.springframework.boot spring-boot-configuration-processor true
三、前两种读取配置的使用方式
//使用方法
privatefinalApplicationPropertyapplicationProperty;
privatefinalDeveloperPropertydeveloperProperty;
@Autowired
publicPropertyController(ApplicationPropertyapplicationProperty,DeveloperPropertydeveloperProperty){
this.applicationProperty=applicationProperty;
this.developerProperty=developerProperty;
}
@GetMapping("/property")
publicDictindex(){
System.out.println("name:"+applicationProperty.getName());
System.out.println("version:"+applicationProperty.getVersion());
System.out.println("DevName:"+applicationProperty.getDeveloperName());
}
四、用Hutool的方式读取配置文件(不支持yml格式)
1.用Props的方式读取
staticPropsprops1=newProps("application.properties",CharsetUtil.CHARSET_UTF_8);
2.用Setting的方法读取
staticSettingsetting=newSetting("application-dev.yml",CharsetUtil.CHARSET_UTF_8,true);
3.将配置文件读取
publicclassConstant{
staticPropsprops1=newProps("application.properties",CharsetUtil.CHARSET_UTF_8);
staticSettingsetting=newSetting("application-dev.properties",CharsetUtil.CHARSET_UTF_8,true);
publicstaticfinalStringName;
publicstaticfinalStringSettingName;
static{
Name=props.getStr("application.name");
SettingName=setting.getByGroup("name","application");
}
}
4.使用方式
System.out.println(Constant.DevName+"------"+Constant.DevWebsite);
直接用常量类调用该类属性即可使用
到此这篇关于浅谈SpringBoot主流读取配置文件三种方式的文章就介绍到这了,更多相关SpringBoot主流读取配置内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!