iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >使用springboot在工具类中读取配置文件(ClassPathResource)
  • 796
分享到

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

2024-04-02 19:04:59 796人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

SpringBoot工具类中读取配置文件 1、创建配置文件(application.properties) spring.activeMQ.broker-url=tcp://lo

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;

@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;

@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;

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();
    }
  }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

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

本文链接: https://www.lsjlt.com/news/132307.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作