java closeutils_java-PropertiesUtils

springboot

springboot下,请直接使用@Value读取配置文件。举个栗子:

@Value("${session.timeout:5000}")

另外:如果对静态变量赋值,有以下两种方法

//1. 通过@PostConstruct注解

@Component

public class Example {

@Autowired

private Environment environment;

public static String value1;

@PostConstruct

public void init(){

value1 = environment.getProperty("spring.value1");

}

}

//2. 通过set方法

@Component

public class Example {

private static String value2;

@Value("${spring.value2}")

public void setValue2(String value) {

Example.value2 = value;

}

自定义工具类

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

/**

* 配置文件工具类

* @author 019530

* @date 2020-07-08

*/

public class PropertiesUtils {

private static String filename = "application.properties";

private static Properties properties = null;

static {

if(null == properties){

properties = new Properties();

InputStream is = null;

try{

is = PropertiesUtils.class.getClassLoader().getResourceAsStream(filename);

properties.load(is);

}catch (Exception e){

e.printStackTrace();

}finally {

try {

if(is != null){

is.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/**

* 获取配置文件

* @param key

* @return

*/

public static String getString(String key){

return properties.getProperty(key);

}

/**

* 获取配置文件,并设置默认值

* @param key

* @param defaultValue

* @return

*/

public static String getProperty(String key, String defaultValue) {

return properties.getProperty(key, defaultValue);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值