前言

在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在Springboot中获取配置文件的方式。

注:前三种测试配置文件为springboot默认的application.properties文件

  1. #######################方式一#########################
  2. com.battle.type3=Springboot - @ConfigurationProperties
  3. com.battle.title3=使用@ConfigurationProperties获取配置文件
  4. #map
  5. com.battle.login[username]=admin
  6. com.battle.login[password]=123456
  7. com.battle.login[callback]=http://www.flyat.cc
  8. #list
  9. com.battle.urls[0]=http://ztool.cc
  10. com.battle.urls[1]=http://ztool.cc/format/js
  11. com.battle.urls[2]=http://ztool.cc/str2image
  12. com.battle.urls[3]=http://ztool.cc/json2Entity
  13. com.battle.urls[4]=http://ztool.cc/ua
  14. #######################方式二#########################
  15. com.battle.type=Springboot - @Value
  16. com.battle.title=使用@Value获取配置文件
  17. #######################方式三#########################
  18. com.battle.type2=Springboot - Environment
  19. com.battle.title2=使用Environment获取配置文件

一、@ConfigurationProperties方式

自定义配置类:PropertiesConfig.java

  1. import java.io.UnsupportedEncodingException;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.springframework.boot.context.properties.ConfigurationProperties;
  7. //import org.springframework.context.annotation.PropertySource;
  8. import org.springframework.stereotype.Component;
  9. /**
  10. * 对应上方配置文件中的第一段配置
  11. * @author battle
  12. * @date 2017年6月1日 下午4:34:18
  13. * @version V1.0
  14. * @since JDK : 1.7 */
  15. @Component
  16. @ConfigurationProperties(prefix = "com.zyd")
  17. // PropertySource默认取application.properties
  18. // @PropertySource(value = "config.properties")
  19. public class PropertiesConfig {
  20. public String type3; public String title3;
  21. public Map<String, String> login = new HashMap<String, String>();
  22. public List<String> urls = new ArrayList<>();
  23. public String getType3() {
  24. return type3;
  25. }
  26. public void setType3(String type3) {
  27. this.type3 = type3;
  28. }
  29. public String getTitle3() {
  30. try {
  31. return new String(title3.getBytes("ISO-8859-1"), "UTF-8");
  32. } catch (UnsupportedEncodingException e) {
  33. e.printStackTrace();
  34. }
  35. return title3;
  36. }
  37. public void setTitle3(String title3) {
  38. this.title3 = title3;
  39. }
  40. public Map<String, String> getLogin() { return login; }
  41. public void setLogin(Map<String, String> login) { this.login = login; }
  42. public List<String> getUrls() { return urls; }
  43. public void setUrls(List<String> urls) { this.urls = urls; } }

程序启动类:Applaction.java

  1. import java.io.UnsupportedEncodingException;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.SpringApplication;
  6. import org.springframework.boot.autoconfigure.SpringBootApplication;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import com.zyd.property.config.PropertiesConfig;
  10. @SpringBootApplication
  11. @RestController
  12. public class Applaction {
  13. @Autowired private PropertiesConfig propertiesConfig;
  14. /**
  15. * 第一种方式:使用`@ConfigurationProperties`注解将配置文件属性注入到配置对象类中
  16. * @throws UnsupportedEncodingException
  17. * @since JDK 1.7 */
  18. @RequestMapping( "/config" ) public Map<String, Object> configurationProperties()
  19. {
  20. Map<String, Object> map = new HashMap<String, Object>();
  21. map.put( "type", propertiesConfig.getType3() );
  22. map.put( "title", propertiesConfig.getTitle3() );
  23. map.put( "login", propertiesConfig.getLogin() );
  24. map.put( "urls", propertiesConfig.getUrls() );
  25. return(map);
  26. }
  27. public static void main( String[] args ) throws Exception
  28. {
  29. SpringApplication application = new SpringApplication( Applaction.class );
  30. application.run( args );
  31. }
  32. }

访问结果:
{"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

  1. import java.io.UnsupportedEncodingException;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.boot.SpringApplication;
  6. import org.springframework.boot.autoconfigure.SpringBootApplication;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @SpringBootApplication
  10. @RestController
  11. public class Applaction {
  12. @Value("${com.zyd.type}") private String type;
  13. @Value("${com.zyd.title}") private String title;
  14. /** * * 第二种方式:使用`@Value("${propertyName}")`注解 *
  15. * @throws UnsupportedEncodingException * @since JDK 1.7 */
  16. @RequestMapping("/value") public Map<String, Object> value() throws UnsupportedEncodingException {
  17. Map<String, Object> map = new HashMap<String, Object>();
  18. map.put("type", type);
  19. // *.properties文件中的中文默认以ISO-8859-1方式编码,因此需要对中文内容进行重新编码
  20. map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));
  21. return map;
  22. }
  23. public static void main(String[] args) throws Exception {
  24. SpringApplication application = new SpringApplication(Applaction.class);
  25. application.run(args);
  26. } }

访问结果:
{"title":"使用@Value获取配置文件","type":"Springboot - @Value"}

三、使用Environment
程序启动类:Applaction.java

  1. import java.io.UnsupportedEncodingException;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.SpringApplication;
  6. import org.springframework.boot.autoconfigure.SpringBootApplication;
  7. import org.springframework.core.env.Environment;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. @SpringBootApplication
  11. @RestController
  12. public class Applaction {
  13. @Autowired private Environment env;
  14. /** * * 第三种方式:使用`Environment` * * @author zyd * @throws UnsupportedEncodingException * @since JDK 1.7 */
  15. @RequestMapping("/env") public Map<String, Object> env() throws UnsupportedEncodingException {
  16. Map<String, Object> map = new HashMap<String, Object>();
  17. map.put("type", env.getProperty("com.zyd.type2"));
  18. map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8"));
  19. return map;
  20. }
  21. public static void main(String[] args) throws Exception {
  22. SpringApplication application = new SpringApplication(Applaction.class);
  23. application.run(args);
  24. }
  25. }

访问结果:
{"title":"使用Environment获取配置文件","type":"Springboot - Environment"}
四、使用PropertiesLoaderUtils
app-config.properties

  1. #### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式
  2. com.battle.type=Springboot - Listeners
  3. com.battle.title=使用Listeners + PropertiesLoaderUtils获取配置文件
  4. com.battle.name=zyd
  5. com.battle.address=Beijing
  6. com.battle.company=in

PropertiesListener.java 用来初始化加载配置文件

  1. import org.springframework.boot.context.event.ApplicationStartedEvent;
  2. import org.springframework.context.ApplicationListener;
  3. import com.zyd.property.config.PropertiesListenerConfig;
  4. public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
  5. private String propertyFileName;
  6. public PropertiesListener(String propertyFileName) {
  7. this.propertyFileName = propertyFileName;
  8. }
  9. @Override public void onApplicationEvent(ApplicationStartedEvent event) {
  10. PropertiesListenerConfig.loadAllProperties(propertyFileName);
  11. }
  12. }

PropertiesListenerConfig.java 加载配置文件内容

  1. import org.springframework.boot.context.event.ApplicationStartedEvent;
  2. import org.springframework.context.ApplicationListener;
  3. import com.zyd.property.config.PropertiesListenerConfig;
  4. public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
  5. private String propertyFileName;
  6. public PropertiesListener(String propertyFileName) {
  7. this.propertyFileName = propertyFileName;
  8. }
  9. @Override public void onApplicationEvent(ApplicationStartedEvent event) {
  10. PropertiesListenerConfig.loadAllProperties(propertyFileName);
  11. }
  12. }

Applaction.java 启动类

  1. import java.io.UnsupportedEncodingException;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import com.zyd.property.config.PropertiesListenerConfig;
  9. import com.zyd.property.listener.PropertiesListener;
  10. @SpringBootApplication @RestController public class Applaction {
  11. /** * * 第四种方式:通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式 * * @author zyd * @throws UnsupportedEncodingException * @since JDK 1.7 */
  12. @RequestMapping("/listener") public Map<String, Object> listener() {
  13. Map<String, Object> map = new HashMap<String, Object>();
  14. map.putAll(PropertiesListenerConfig.getAllProperty());
  15. return map;
  16. }
  17. public static void main(String[] args) throws Exception {
  18. SpringApplication application = new SpringApplication(Applaction.class);
  19. // 第四种方式:注册监听器 application.addListeners(new PropertiesListener("app-config.properties")); application.run(args); } }

访问结果:

    1. {"com.battle.name":"zyd",
    2. "com.battle.address":"Beijing",
    3. "com.battle.title":"使用Listeners + PropertiesLoaderUtils获取配置文件",
    4. "com.battle.type":"Springboot - Listeners",
    5. "com.battle.company":"in"}

SpringBoot:四种读取properties文件的方式的更多相关文章

  1. SpringBoot四种读取properties文件的方式

    环境:IDEA jdk1.8 SpringBoot2.1.4 例,如下默认application.properties文件   一.使用`@ConfigurationProperties`注解将配置文 ...

  2. SpringBoot的读取properties文件的方式

    转载:https://www.imooc.com/article/18252一.@ConfigurationProperties方式 自定义配置类:PropertiesConfig.java pack ...

  3. 五种方式让你在java中读取properties文件内容不再是难题

    一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...

  4. 【开发笔记】- Java读取properties文件的五种方式

    原文地址:https://www.cnblogs.com/hafiz/p/5876243.html 一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供j ...

  5. Java 读取 .properties 文件的几种方式

    Java 读取 .properties 配置文件的几种方式   Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 ...

  6. 用类加载器的5种方式读取.properties文件

    用类加载器的5中形式读取.properties文件(这个.properties文件一般放在src的下面) 用类加载器进行读取:这里采取先向大家讲读取类加载器的几种方法:然后写一个例子把几种方法融进去, ...

  7. SpringBoot @Value读取properties文件的属性

    SpringBoot在application.properties文件中,可以自定义属性. 在properties文件中如下示: #自定义属性 mail.fromMail.addr=lgr@163.c ...

  8. java分享第十六天( java读取properties文件的几种方法&java配置文件持久化:static块的作用)

     java读取properties文件的几种方法一.项目中经常会需要读取配置文件(properties文件),因此读取方法总结如下: 1.通过java.util.Properties读取Propert ...

  9. springBoot使用@Value标签读取*.properties文件的中文乱码问题

    上次我碰到获取properties文件中的中文出现乱码问题. 查了下资料,原来properties默认的字符编码格式为asci码,所以我们要对字符编码进行转换成UTF-8格式 原先代码:@Proper ...

随机推荐

  1. numpy.trace对于三维以上array的解析

    numpy.trace是求shape的对角线上的元素的和,具体看 https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.t ...

  2. 【ASP.NET 问题】ASP.NET 网站404页面返回200,或者302的解决办法

    做网站在优化网站时遇到了跳转404页面却返回 200.302状态的问题,这样的话搜索引擎会认为这个页面是一个正常的页面,但是这个页面实际是个错误页面,虽然对访问的用户而言,HTTP状态码是“404”还 ...

  3. apache配置伪静态Rewrite

    1: 修改apache的httpd.conf文件 找到这一行 #LoadModule rewrite_module modules/mod_rewrite.so 改成 LoadModule rewri ...

  4. NYOJ127 星际之门(一)【定理】

    星际之门(一) 时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描写叙述 公元3000年,子虚帝国统领着N个星系,原先它们是靠近光束飞船来进行旅行的,近来,X博士发明了星际之门 ...

  5. android编码学习

    虽然以下博客有点老,但很清晰,有不明白的基础知识,可以来这里找找. 2015年最新Android基础入门教程目录(完结版) 1. 环境配置 Android stodio gradle配置踩过的坑 An ...

  6. Python 进制转换 二进制 八进制 十进制 十六进制

    Python 进制转换 二进制 八进制 十进制 十六进制 作者:方倍工作室 地址:http://www.cnblogs.com/txw1958/p/python3-scale.html 全局定义一定不 ...

  7. STM32F105 PA9/OTG_FS_VBUS Issues

    https://www.cnblogs.com/shangdawei/p/3264724.html F105 DFU模式下PA9引脚用来检测USB线缆,若电平在2.7~5v则认为插入usb设备(检测到 ...

  8. 我的IT之路这样走过

    一.我的IT之路这样走过: 1.大一上学期.我们学校是用C语言做启蒙语言的:虽然我学的相当不错,但是我发现一个问题:用C语言做软件那么它的交付周期比较长. 对于我这种无产阶级来说最关键的是解眼下的粮食 ...

  9. Linux Shell 运算符

    Shell 和其他编程语言一样,支持多种运算符,包括: 算数运算符 关系运算符 布尔运算符 逻辑运算符 字符串运算符 文件测试运算符 原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 ...

  10. MySql 三大知识点——索引、锁、事务

    1. 索引 索引,类似书籍的目录,可以根据目录的某个页码立即找到对应的内容. 索引的优点:1. 天生排序.2. 快速查找.索引的缺点:1. 占用空间.2. 降低更新表的速度. 注意点:小表使用全表扫描 ...