SpringBoot四种读取properties文件的方式(小结)

 更新时间:2020年05月27日 09:08:28   作者:猿敲月下码  
这篇文章主要介绍了SpringBoot四种读取properties文件的方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作。今天就分享四种在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"}

到此这篇关于SpringBoot四种读取properties文件的方式(小结)的文章就介绍到这了,更多相关SpringBoot读取properties文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java 实现将Object类型转换为int类型

    java 实现将Object类型转换为int类型

    这篇文章主要介绍了java 实现将Object类型转换为int类型的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • JAVA垃圾收集器与内存分配策略详解

    JAVA垃圾收集器与内存分配策略详解

    这篇文章介绍了JAVA垃圾收集器与内存分配策略,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2015-07-07
  • SpringBoot对静态资源的映射规则详解解读

    SpringBoot对静态资源的映射规则详解解读

    这篇文章主要介绍了SpringBoot对静态资源的映射规则详解解读,在Spring Boot中,映射规则是用来定义URL与控制器方法之间的映射关系的,通过映射规则,可以将特定的URL请求映射到相应的控制器方法上,从而实现请求的处理和响应的返回,需要的朋友可以参考下
    2023-10-10
  • 十五道tomcat面试题,为数不多的机会!

    十五道tomcat面试题,为数不多的机会!

    这篇文章主要介绍了十五道tomcat面试题,Tomcat的本质是一个Servlet容器。一个Servlet能做的事情是:处理请求资源,并为客户端填充response对象,需要的朋友可以参考下
    2021-08-08
  • 最新springboot解决跨域的几种方式小结

    最新springboot解决跨域的几种方式小结

    跨域指的是浏览器不能执⾏其他⽹站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制,这篇文章主要介绍了springboot解决跨域的几种方式,需要的朋友可以参考下
    2022-05-05
  • SpringBoot使用Redis方式

    SpringBoot使用Redis方式

    文章介绍了SpringDataRedis操作本地Redis数据库的方法,包括Redis的基本概念、数据类型、命令以及在Java中的使用
    2024-11-11
  • 如何利用Java Agent 做Spring MVC Controller 层的出参入参打印日志

    如何利用Java Agent 做Spring MVC Controller 层的出参入参打印日志

    本文介绍了如何使用JavaAgent进行Spring MVC Controller层的出参入参打印日志,首先,建立了一个包含javassist和fastJSON依赖的Agent jar工程,并创建了一个Agent类,然后,编译并部署了这个Agent jar,最后,在Demo Web工程中启用Agent以实现日志打印
    2024-11-11
  • Java中的函数式编程

    Java中的函数式编程

    这篇文章介绍Java中的函数式编程,函数式编程是一种编程范式,其中程序是通过应用和组合函数来构造的。它是一种声明式编程范式,其中函数定义是表达式树,每个表达式树返回一个值,而不是一系列改变程序状态的命令语句,具体情况请看下文,希望对你有所帮助
    2021-10-10
  • SpringMVC如何域对象共享数据

    SpringMVC如何域对象共享数据

    在Spring MVC中,可以使用域对象来共享数据,域对象是一个Map类型的对象,可以在请求处理方法之间共享数据,本文给大家介绍SpringMVC 域对象共享数据的示例代码,一起看看吧
    2023-09-09
  • Java中Map.merge()方法使用示例详解

    Java中Map.merge()方法使用示例详解

    这篇文章主要介绍了Map.merge()方法使用和介绍,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08

最新评论