SpringBoot四种读取properties文件的方式(小结)
作者:猿敲月下码 发布时间:2023-10-10 03:25:14
前言
在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在Springboot中获取配置文件的方式。
注:前三种测试配置文件为springboot默认的application.properties文件
#######################方式一#########################
com.zyd.type3=Springboot - @ConfigurationProperties
com.zyd.title3=使用@ConfigurationProperties获取配置文件
#map
com.zyd.login[username]=zhangdeshuai
com.zyd.login[password]=zhenshuai
com.zyd.login[callback]=http://www.flyat.cc
#list
com.zyd.urls[0]=http://ztool.cc
com.zyd.urls[1]=http://ztool.cc/format/js
com.zyd.urls[2]=http://ztool.cc/str2image
com.zyd.urls[3]=http://ztool.cc/json2Entity
com.zyd.urls[4]=http://ztool.cc/ua
#######################方式二#########################
com.zyd.type=Springboot - @Value
com.zyd.title=使用@Value获取配置文件
#######################方式三#########################
com.zyd.type2=Springboot - Environment
com.zyd.title2=使用Environment获取配置文件
一、@ConfigurationProperties方式
自定义配置类:PropertiesConfig.java
package com.zyd.property.config;
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 <a href="mailto:yadong.zhang0415@gmail.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >yadong.zhang</a>
* @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
package com.zyd.property;
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;
/**
* @author <a href="mailto:yadong.zhang0415@gmail.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private PropertiesConfig propertiesConfig;
/**
*
* 第一种方式:使用`@ConfigurationProperties`注解将配置文件属性注入到配置对象类中
*
* @author zyd
* @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":"zhangdeshuai","callback":"http://www.flyat.cc","password":"zhenshuai"},"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;
/**
* @author <a href="mailto:yadong.zhang0415@gmail.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@SpringBootApplication
@RestController
public class Applaction {
@Value("${com.zyd.type}")
private String type;
@Value("${com.zyd.title}")
private String title;
/**
*
* 第二种方式:使用`@Value("${propertyName}")`注解
*
* @author zyd
* @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
package com.zyd.property;
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;
/**
* @author <a href="mailto:yadong.zhang0415@gmail.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@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.zyd.type=Springboot - Listeners
com.zyd.title=使用Listeners + PropertiesLoaderUtils获取配置文件
com.zyd.name=zyd
com.zyd.address=Beijing
com.zyd.company=in
PropertiesListener.java 用来初始化加载配置文件
package com.zyd.property.listener;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import com.zyd.property.config.PropertiesListenerConfig;
/**
* 配置文件 * ,用来加载自定义配置文件
*
* @author <a href="mailto:yadong.zhang0415@gmail.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >yadong.zhang</a>
* @date 2017年6月1日 下午3:38:25
* @version V1.0
* @since JDK : 1.7
*/
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 加载配置文件内容
package com.zyd.property.config;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.core.io.support.PropertiesLoaderUtils;
/**
* 第四种方式:PropertiesLoaderUtils
*
* @author <a href="mailto:yadong.zhang0415@gmail.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >yadong.zhang</a>
* @date 2017年6月1日 下午3:32:37
* @version V1.0
* @since JDK : 1.7
*/
public class PropertiesListenerConfig {
public static Map<String, String> propertiesMap = new HashMap<>();
private static void processProperties(Properties props) throws BeansException {
propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
try {
// PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}
public static void loadAllProperties(String propertyFileName) {
try {
Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
processProperties(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String name) {
return propertiesMap.get(name).toString();
}
public static Map<String, String> getAllProperty() {
return propertiesMap;
}
}
Applaction.java 启动类
package com.zyd.property;
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;
/**
* @author <a href="mailto:yadong.zhang0415@gmail.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >yadong.zhang</a>
* @date 2017年6月1日 下午3:49:30
* @version V1.0
* @since JDK : 1.7
*/
@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.zyd.name":"zyd","com.zyd.address":"Beijing","com.zyd.title":"使用Listeners + PropertiesLoaderUtils获取配置文件","com.zyd.type":"Springboot - Listeners","com.zyd.company":"in"}
来源:https://blog.csdn.net/thc1987/article/details/78789426
猜你喜欢
- 概述本文的编写初衷,是想了解一下Spring Boot2中,具体是怎么序列化和反序列化JSR 310日期时间体系的,Spring MVC应用
- Java 内存划分: 在Java内存分配中,java将内存分为:方法区,堆,虚拟机栈,本地方法栈,程序计
- 最近因为项目的国际化的需要,需要对整个项目的100来个插件做国际化,这是一件痛苦的事情,因为纯体力劳动。为了省点工作量,想着能不能写个程序批
- 目录1. List1.1 List 的常见方法1.2 代码示例2. ArrayList2.1 介绍2.2 ArrayList 的构造方法2.
- 大家好,欢迎来到老胡的博客,今天我们继续了解设计模式中的职责链模式,这是一个比较简单的模式。跟往常一样,我们还是从一个真实世界的例子入手,这
- 本文实例分析了采用C#实现软件自动更新的方法,是非常实用的功能,值得学习和借鉴。具体如下:1.问题概述:长期以来,广大程序员为到底是使用Cl
- 基于jsr303 通过自定义注解实现,实现思路:存在一些瑕疵,后续补充完善。加入依赖部分版本已不默认自动引入该依赖,选择手动引入<de
- Java的Arrays类中有一个sort()方法,该方法是Arrays类的静态方法,在需要对数组进行排序时,非常的好用。但是sort()的参
- 在很多场景下,maven不能直接访问到外网时,使用代理是其中常见的一种方式。这篇文章整理一下常见的maven中设置代理的方法。代理服务器代理
- 前言当系统的并发比较高的时候,日志的处理输出也是一种性能的开销负担,所以,选择一个中间件来处理消费日志必不可少!下面是spring boot
- 一、 java文件中获得路径Thread.currentThread().getContextClassLoader().getResour
- 本文主要介绍的是通过使用java的相关类可以实现对文件或文件夹的压缩。zlib是一种数据压缩程序库,它的设计目标是处理单纯的数据(而不管数据
- android原生的Spinner提供了下拉列表选项框,但在一些流行的APP中,原生的Spinner似乎不太受待见,而通常会有下图所示的下拉
- 引言前一段有幸参与到一个智能家居项目的开发,由于之前都没有过这方面的开发经验,所以对智能硬件的开发模式和技术栈都颇为好奇。智能可燃气体报警器
- 将图片上传到webapp路径下 路径获取方式此方法获取到工程webapp文件夹下String contexPath= request.get
- 这篇文章需要对git具有一定的了解,并且知道如何安装git工具(其实就是上git官网下载个文件,安装)git这种版本控制工具有什么好处第一个
- 线程中断机制提供了一种方法,用于将线程从阻塞等待中唤醒,尝试打断目标线程的现有处理流程,使之响应新的命令。Java 留给开发者这一自由,我们
- 在开发过程中,我们需要统一返回前端json格式的数据,但有些接口的返回值存在 null或者""这种没有意义的字段。不仅影
- 今天去某在线教育面试面试官让做的一道题,题目描述如下:给定一个不重复的无序数组arr和一个定值num查找arr中是否有两个数的和等于num有
- 本文实例为大家分享了C#实现剪刀石头布游戏的具体代码,供大家参考,具体内容如下游戏界面如下所示:首先我们必须知道要创建三个类玩家类,电脑类,