读取配置SpringBoot配置文件三种方式
一、利用Bean注解中的Value(${})注解
1
2
3
4
5
6
|
@Data
@Component
public class ApplicationProperty {
@Value ( "${application.name}" )
private String name;
}
|
该方式可以自动读取当前配置文件appliation.yml 或者application.properties中的配置值
区别在于读取yml文件时候支持中文编码,peoperties需要转码
二、利用@ConfigurationProperties(prefix = "developer")注解
1
2
3
4
5
6
7
8
9
|
@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文件中引入依赖
1
2
3
4
5
|
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-configuration-processor</ artifactId >
< optional >true</ optional >
</ dependency >
|
三、前两种读取配置的使用方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//使用方法
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的方式读取
1
|
static Props props1 = new Props( "application.properties" ,CharsetUtil.CHARSET_UTF_8);
|
2.用Setting的方法读取
1
|
static Setting setting = new Setting( "application-dev.yml" , CharsetUtil.CHARSET_UTF_8, true );
|
3.将配置文件读取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class Constant {
static Props props1 = new Props( "application.properties" ,CharsetUtil.CHARSET_UTF_8);
static Setting setting = new Setting( "application-dev.properties" , CharsetUtil.CHARSET_UTF_8, true );
public static final String Name ;
public static final String SettingName ;
static {
Name = props.getStr( "application.name" );
SettingName = setting.getByGroup( "name" , "application" );
}
}
|
4.使用方式
1
|
System.out.println(Constant.DevName+ "------" +Constant.DevWebsite);
|
直接用常量类调用该类属性即可使用
到此这篇关于浅谈SpringBoot主流读取配置文件三种方式的文章就介绍到这了,更多相关SpringBoot主流读取配置内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.im/post/6873648875345805320