SpringBoot:四种读取properties文件的方式
前言
在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在Springboot中获取配置文件的方式。
注:前三种测试配置文件为springboot默认的application.properties文件
- #######################方式一#########################
- com.battle.type3=Springboot - @ConfigurationProperties
- com.battle.title3=使用@ConfigurationProperties获取配置文件
- #map
- com.battle.login[username]=admin
- com.battle.login[password]=123456
- com.battle.login[callback]=http://www.flyat.cc
- #list
- com.battle.urls[0]=http://ztool.cc
- com.battle.urls[1]=http://ztool.cc/format/js
- com.battle.urls[2]=http://ztool.cc/str2image
- com.battle.urls[3]=http://ztool.cc/json2Entity
- com.battle.urls[4]=http://ztool.cc/ua
- #######################方式二#########################
- com.battle.type=Springboot - @Value
- com.battle.title=使用@Value获取配置文件
- #######################方式三#########################
- com.battle.type2=Springboot - Environment
- com.battle.title2=使用Environment获取配置文件
一、@ConfigurationProperties方式
自定义配置类:PropertiesConfig.java
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- //import org.springframework.context.annotation.PropertySource;
- import org.springframework.stereotype.Component;
- /**
- * 对应上方配置文件中的第一段配置
- * @author battle
- * @date 2017年6月1日 下午4:34:18
- * @version V1.0
- * @since JDK : 1.7 */
- @Component
- @ConfigurationProperties(prefix = "com.zyd")
- // PropertySource默认取application.properties
- // @PropertySource(value = "config.properties")
- public class PropertiesConfig {
- public String type3; public String title3;
- public Map<String, String> login = new HashMap<String, String>();
- public List<String> urls = new ArrayList<>();
- public String getType3() {
- return type3;
- }
- public void setType3(String type3) {
- this.type3 = type3;
- }
- public String getTitle3() {
- try {
- return new String(title3.getBytes("ISO-8859-1"), "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return title3;
- }
- public void setTitle3(String title3) {
- this.title3 = title3;
- }
- public Map<String, String> getLogin() { return login; }
- public void setLogin(Map<String, String> login) { this.login = login; }
- public List<String> getUrls() { return urls; }
- public void setUrls(List<String> urls) { this.urls = urls; } }
程序启动类:Applaction.java
- import java.io.UnsupportedEncodingException;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import com.zyd.property.config.PropertiesConfig;
- @SpringBootApplication
- @RestController
- public class Applaction {
- @Autowired private PropertiesConfig propertiesConfig;
- /**
- * 第一种方式:使用`@ConfigurationProperties`注解将配置文件属性注入到配置对象类中
- * @throws UnsupportedEncodingException
- * @since JDK 1.7 */
- @RequestMapping( "/config" ) public Map<String, Object> configurationProperties()
- {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put( "type", propertiesConfig.getType3() );
- map.put( "title", propertiesConfig.getTitle3() );
- map.put( "login", propertiesConfig.getLogin() );
- map.put( "urls", propertiesConfig.getUrls() );
- return(map);
- }
- public static void main( String[] args ) throws Exception
- {
- SpringApplication application = new SpringApplication( Applaction.class );
- application.run( args );
- }
- }
访问结果:
{"title":"使用@ConfigurationProperties获取配置文件",
"urls":["http://ztool.cc","http://ztool.cc/format/js","http://ztool.cc/str2image",
"http://ztool.cc/json2Entity","http://ztool.cc/ua"],
"login":{"username":"admin",
"callback":"http://www.flyat.cc","password":"123456"},
"type":"Springboot - @ConfigurationProperties"}
二、使用@Value注解方式
程序启动类:Applaction.java
- import java.io.UnsupportedEncodingException;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @SpringBootApplication
- @RestController
- public class Applaction {
- @Value("${com.zyd.type}") private String type;
- @Value("${com.zyd.title}") private String title;
- /** * * 第二种方式:使用`@Value("${propertyName}")`注解 *
- * @throws UnsupportedEncodingException * @since JDK 1.7 */
- @RequestMapping("/value") public Map<String, Object> value() throws UnsupportedEncodingException {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("type", type);
- // *.properties文件中的中文默认以ISO-8859-1方式编码,因此需要对中文内容进行重新编码
- map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));
- return map;
- }
- public static void main(String[] args) throws Exception {
- SpringApplication application = new SpringApplication(Applaction.class);
- application.run(args);
- } }
访问结果:
{"title":"使用@Value获取配置文件","type":"Springboot - @Value"}
三、使用Environment
程序启动类:Applaction.java
- import java.io.UnsupportedEncodingException;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.core.env.Environment;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @SpringBootApplication
- @RestController
- public class Applaction {
- @Autowired private Environment env;
- /** * * 第三种方式:使用`Environment` * * @author zyd * @throws UnsupportedEncodingException * @since JDK 1.7 */
- @RequestMapping("/env") public Map<String, Object> env() throws UnsupportedEncodingException {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("type", env.getProperty("com.zyd.type2"));
- map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8"));
- return map;
- }
- public static void main(String[] args) throws Exception {
- SpringApplication application = new SpringApplication(Applaction.class);
- application.run(args);
- }
- }
访问结果:
{"title":"使用Environment获取配置文件","type":"Springboot - Environment"}
四、使用PropertiesLoaderUtils
app-config.properties
- #### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式
- com.battle.type=Springboot - Listeners
- com.battle.title=使用Listeners + PropertiesLoaderUtils获取配置文件
- com.battle.name=zyd
- com.battle.address=Beijing
- com.battle.company=in
PropertiesListener.java 用来初始化加载配置文件
- import org.springframework.boot.context.event.ApplicationStartedEvent;
- import org.springframework.context.ApplicationListener;
- import com.zyd.property.config.PropertiesListenerConfig;
- public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
- private String propertyFileName;
- public PropertiesListener(String propertyFileName) {
- this.propertyFileName = propertyFileName;
- }
- @Override public void onApplicationEvent(ApplicationStartedEvent event) {
- PropertiesListenerConfig.loadAllProperties(propertyFileName);
- }
- }
PropertiesListenerConfig.java 加载配置文件内容
- import org.springframework.boot.context.event.ApplicationStartedEvent;
- import org.springframework.context.ApplicationListener;
- import com.zyd.property.config.PropertiesListenerConfig;
- public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
- private String propertyFileName;
- public PropertiesListener(String propertyFileName) {
- this.propertyFileName = propertyFileName;
- }
- @Override public void onApplicationEvent(ApplicationStartedEvent event) {
- PropertiesListenerConfig.loadAllProperties(propertyFileName);
- }
- }
Applaction.java 启动类
- import java.io.UnsupportedEncodingException;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import com.zyd.property.config.PropertiesListenerConfig;
- import com.zyd.property.listener.PropertiesListener;
- @SpringBootApplication @RestController public class Applaction {
- /** * * 第四种方式:通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式 * * @author zyd * @throws UnsupportedEncodingException * @since JDK 1.7 */
- @RequestMapping("/listener") public Map<String, Object> listener() {
- Map<String, Object> map = new HashMap<String, Object>();
- map.putAll(PropertiesListenerConfig.getAllProperty());
- return map;
- }
- public static void main(String[] args) throws Exception {
- SpringApplication application = new SpringApplication(Applaction.class);
- // 第四种方式:注册监听器 application.addListeners(new PropertiesListener("app-config.properties")); application.run(args); } }
访问结果:
- {"com.battle.name":"zyd",
- "com.battle.address":"Beijing",
- "com.battle.title":"使用Listeners + PropertiesLoaderUtils获取配置文件",
- "com.battle.type":"Springboot - Listeners",
- "com.battle.company":"in"}
SpringBoot:四种读取properties文件的方式的更多相关文章
- SpringBoot四种读取properties文件的方式
环境:IDEA jdk1.8 SpringBoot2.1.4 例,如下默认application.properties文件 一.使用`@ConfigurationProperties`注解将配置文 ...
- SpringBoot的读取properties文件的方式
转载:https://www.imooc.com/article/18252一.@ConfigurationProperties方式 自定义配置类:PropertiesConfig.java pack ...
- 五种方式让你在java中读取properties文件内容不再是难题
一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...
- 【开发笔记】- Java读取properties文件的五种方式
原文地址:https://www.cnblogs.com/hafiz/p/5876243.html 一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供j ...
- Java 读取 .properties 文件的几种方式
Java 读取 .properties 配置文件的几种方式 Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 ...
- 用类加载器的5种方式读取.properties文件
用类加载器的5中形式读取.properties文件(这个.properties文件一般放在src的下面) 用类加载器进行读取:这里采取先向大家讲读取类加载器的几种方法:然后写一个例子把几种方法融进去, ...
- SpringBoot @Value读取properties文件的属性
SpringBoot在application.properties文件中,可以自定义属性. 在properties文件中如下示: #自定义属性 mail.fromMail.addr=lgr@163.c ...
- java分享第十六天( java读取properties文件的几种方法&java配置文件持久化:static块的作用)
java读取properties文件的几种方法一.项目中经常会需要读取配置文件(properties文件),因此读取方法总结如下: 1.通过java.util.Properties读取Propert ...
- springBoot使用@Value标签读取*.properties文件的中文乱码问题
上次我碰到获取properties文件中的中文出现乱码问题. 查了下资料,原来properties默认的字符编码格式为asci码,所以我们要对字符编码进行转换成UTF-8格式 原先代码:@Proper ...
随机推荐
- numpy.trace对于三维以上array的解析
numpy.trace是求shape的对角线上的元素的和,具体看 https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.t ...
- 【ASP.NET 问题】ASP.NET 网站404页面返回200,或者302的解决办法
做网站在优化网站时遇到了跳转404页面却返回 200.302状态的问题,这样的话搜索引擎会认为这个页面是一个正常的页面,但是这个页面实际是个错误页面,虽然对访问的用户而言,HTTP状态码是“404”还 ...
- apache配置伪静态Rewrite
1: 修改apache的httpd.conf文件 找到这一行 #LoadModule rewrite_module modules/mod_rewrite.so 改成 LoadModule rewri ...
- NYOJ127 星际之门(一)【定理】
星际之门(一) 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描写叙述 公元3000年,子虚帝国统领着N个星系,原先它们是靠近光束飞船来进行旅行的,近来,X博士发明了星际之门 ...
- android编码学习
虽然以下博客有点老,但很清晰,有不明白的基础知识,可以来这里找找. 2015年最新Android基础入门教程目录(完结版) 1. 环境配置 Android stodio gradle配置踩过的坑 An ...
- Python 进制转换 二进制 八进制 十进制 十六进制
Python 进制转换 二进制 八进制 十进制 十六进制 作者:方倍工作室 地址:http://www.cnblogs.com/txw1958/p/python3-scale.html 全局定义一定不 ...
- STM32F105 PA9/OTG_FS_VBUS Issues
https://www.cnblogs.com/shangdawei/p/3264724.html F105 DFU模式下PA9引脚用来检测USB线缆,若电平在2.7~5v则认为插入usb设备(检测到 ...
- 我的IT之路这样走过
一.我的IT之路这样走过: 1.大一上学期.我们学校是用C语言做启蒙语言的:虽然我学的相当不错,但是我发现一个问题:用C语言做软件那么它的交付周期比较长. 对于我这种无产阶级来说最关键的是解眼下的粮食 ...
- Linux Shell 运算符
Shell 和其他编程语言一样,支持多种运算符,包括: 算数运算符 关系运算符 布尔运算符 逻辑运算符 字符串运算符 文件测试运算符 原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 ...
- MySql 三大知识点——索引、锁、事务
1. 索引 索引,类似书籍的目录,可以根据目录的某个页码立即找到对应的内容. 索引的优点:1. 天生排序.2. 快速查找.索引的缺点:1. 占用空间.2. 降低更新表的速度. 注意点:小表使用全表扫描 ...