gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 32 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章使用springboot在工具类中读取配置文件(ClassPathResource)由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

springboot工具类中读取配置文件

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

?
1
2
3
4
5
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)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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)

?
1
2
3
4
5
6
7
8
9
10
11
12
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在工具类中读取配置文件(ClassPathResource)

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

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

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

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

不废话了,直接上代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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与工具类的静态变量名写成一样的即可.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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的版本.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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();
     }
   }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我.

原文链接:https://blog.csdn.net/weixin_45739720/article/details/103701627 。

最后此篇关于使用springboot在工具类中读取配置文件(ClassPathResource)的文章就讲到这里了,如果你想了解更多关于使用springboot在工具类中读取配置文件(ClassPathResource)的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com