使用springboot在工具类中读取配置文件(ClassPathResource)

 更新时间:2021年08月11日 10:59:46   作者:知识追求者  
这篇文章主要介绍了使用springboot在工具类中读取配置文件(ClassPathResource),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

springboot工具类中读取配置文件

1、创建配置文件(application.properties)

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false

2、创建工具类(PropertiesUtil.java)

package com.jeff.utils;
import java.io.IOException;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class PropertiesUtil {
	private static String user;
	static {
		System.out.println("application.properties属性文件读取开始");
		ClassPathResource resource = new ClassPathResource("application.properties");
		try {
			Properties properties = PropertiesLoaderUtils.loadProperties(resource);
			user = properties.getProperty("spring.activemq.user");
			System.out.println("user的值:" + user);
		} catch (IOException e) {
			System.out.println("application.properties属性文件读取异常" + e);
		}
		System.out.println("application.properties属性文件读取完成");
	}
	public static String getUser() {
		System.out.println("获取user的值:" + user);
		return user;
	}
}

3、创建测试类(MyController.java)

package com.jeff.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jeff.utils.PropertiesUtil;
@RestController
public class MyController {
	@RequestMapping("myTest")
	public String myTest() {
		PropertiesUtil.getUser();
		return "success";
	}
}

4、打开浏览器访问 http://localhost:8080/myTest,控制台输出结果

在这里插入图片描述

在这里插入图片描述

springboot读取配置文件到静态工具类

通常我们读取配置文件可以用@Value注解和@Configuration,@ConfigurationProperties(prefix = "xxx")等注解,但是这种方式是无法把配置读取到静态变量的,如果我们想在项目初始化时把配置文件加载到一个工具类,然后通过静态变量的方式调用的话我们就不能使用这两种方法。

这时候,我们可以用Environment 来解决

不废话了,直接上代码

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
 * 
 * @Description: 配置常量类——根据不同的spring-profile加载不同的配置
 * @author: eric.zhang
 * @date: 2018年7月20日 上午10:59:24
 */
@Component
public class ConfigConstant {
  @Autowired
  private Environment env;
  
  public static String url;
  public static String param;
  
  @PostConstruct
  public void readConfig() {
    url = env.getProperty("config.url");
    param = env.getProperty("config.param");
  }
}

我写完以后发现有些麻烦,下面是改进的方法,不需要每个配置都去get一下,只需要把配置文件的key与工具类的静态变量名写成一样的即可。

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
 * 
 * @Description: 配置常量类——根据不同的spring-profile加载不同的配置,变量名要与配置文件里写的名一致
 * @author: eric.zhang
 * @date: 2018年7月20日 上午10:59:24
 */
@Component
public class ConfigConstant {
  @Autowired
  private Environment env;
  
  public static String url;
  public static String name;
  
  
  @PostConstruct
  public void readConfig() throws Exception {
    String prefix = "config.";
    Field[] fields = ConfigConstant.class.getFields();
    for(Field field : fields ){
      field.set(null, getProperty(prefix + field.getName()));
    }
  }
  
  private String getProperty(String key) throws UnsupportedEncodingException {
    return new String(env.getProperty(key).getBytes("ISO-8859-1"), "UTF-8");
  }
}

大哥说这样写依赖spring, 单测调代码的时候不方便,所以又写了一个不依赖spring的版本。

import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Properties;
/**
 * 
 * @Description: 配置常量类——根据不同的spring-profile加载不同的配置
 *               变量名把配置文件的key中的"."替换成"_"命名
 * @author: eric.zhang
 * @date: 2018年7月20日 上午10:59:24
 */
public class ConfigConstant {
  public static String CONFIG_URL;
  public static String CONFIG_NAME;
  static {
    try {
      Properties props = new Properties();
      props.load(new InputStreamReader(
          ConfigConstant.class.getClassLoader().getResourceAsStream("application.properties"),
          "UTF-8"));
      String profile = props.getProperty("spring.profiles.active");
      String envFile = "application-" + profile + ".properties";
      Properties envProps = new Properties();
      envProps.load(new InputStreamReader(
          ConfigConstant.class.getClassLoader().getResourceAsStream(envFile), "UTF-8"));
      Field[] fields = ConfigConstant.class.getFields();
      for (Field field : fields) {
        field.set(null, envProps.getProperty(field.getName().replace("_", ".").toLowerCase()));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Spring Security结合JWT的方法教程

    Spring Security结合JWT的方法教程

    这篇文章主要给大家介绍了关于Spring Security结合JWT的方法教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-12-12
  • springboot多模块包扫描问题的解决方法

    springboot多模块包扫描问题的解决方法

    这篇文章主要介绍了springboot多模块包扫描问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • spring boot获取session的值为null问题及解决方法

    spring boot获取session的值为null问题及解决方法

    我在登陆的时候,登陆成功后将name存进了session,然后在获取个人信息时取出session里的name的值为null,接下来通过本文给大家分享springboot获取session的值为null问题,需要的朋友可以参考下
    2023-05-05
  • Java常见异常及处理方式总结

    Java常见异常及处理方式总结

    今天给大家带来的是Java的相关知识,文章围绕着Java异常展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • 深入理解java的异常情况

    深入理解java的异常情况

    在本篇文章里小编给大家分享了关于Java的异常类型的相关知识点内容,有需要的朋友们跟着学习下,希望能够给你带来帮助
    2021-09-09
  • 解析本地方法映射Java层的数据类型

    解析本地方法映射Java层的数据类型

    这篇文章给大家介绍了本地方法映射Java层的数据类型,包括基础类型映射,引用类型映射等等,对java层数据类型映射相关知识,感兴趣的朋友跟随脚本之家小编一起看看吧
    2018-03-03
  • java正则表达式用法大全(深度好文)

    java正则表达式用法大全(深度好文)

    这篇文章主要给大家介绍了关于java正则表达式用法大全的相关资料,正则表达式在处理字符串时非常有用,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-10-10
  • 关于Java双大括号{{}}的具体使用

    关于Java双大括号{{}}的具体使用

    本文主要介绍了关于Java双大括号{{}}的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • 详解Java如何实现一个像String一样不可变的类

    详解Java如何实现一个像String一样不可变的类

    说到 String 大家都知道 String 是一个不可变的类;虽然用的很多,那不知道小伙伴们有没有想过怎么样创建一个自己的不可变的类呢?这篇文章就带大家来实践一下,创建一个自己的不可变的类
    2022-11-11
  • 跟我学Java Swing之游戏设计(1)

    跟我学Java Swing之游戏设计(1)

    跟我学Java Swing之游戏设计(1)...
    2006-12-12

最新评论