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);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。