您的位置:首页技术文章
文章详情页

浅谈SpringBoot主流读取配置文件三种方式

【字号: 日期:2023-04-22 18:09:53浏览:6作者:猪猪

读取配置SpringBoot配置文件三种方式

一、利用Bean注解中的Value(${})注解

@Data@Componentpublic class ApplicationProperty { @Value('${application.name}') private String name;}

该方式可以自动读取当前配置文件appliation.yml 或者application.properties中的配置值区别在于读取yml文件时候支持中文编码,peoperties需要转码

二、利用@ConfigurationProperties(prefix = 'developer')注解

@Data@ConfigurationProperties(prefix = 'developer')@Componentpublic 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', 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.使用方式

System.out.println(Constant.DevName+'------'+Constant.DevWebsite);

直接用常量类调用该类属性即可使用

到此这篇关于浅谈SpringBoot主流读取配置文件三种方式的文章就介绍到这了,更多相关SpringBoot主流读取配置内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Spring
相关文章: