java通过PropertiesUtils工具类读取properties文件

有些时候不是所有的类都能被spring管理,在spring项目中被spring纳入管理的类里可以直接通过@Value("${属性key}")的方式拿取properties文件里定义的key和value值
如:

package cn.ways.gtids.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


@Component
@PropertySource("classpath:application.properties")
public class ApplicationParams {

    /**
     * 图片服务器
     */
    @Value("${IMAGES_IP_PORT}") public String IMAGES_IP_PORT;

}

但是当不被spring所管理的类如何拿到properties文件里的值呢,java可以通过InputStream来读取properties文件并转化成Properties类来拿取,
如下面的PropertiesUtils工具类:

package cn.ways.util;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

public class PropertiesUtils {
    private static Properties bootstrapProperties;
    private static String SPRING_FILE_ACTIVE;

    static {
        bootstrapProperties = new Properties();
        InputStream bootstrapInstream = PropertiesUtils.class.getClassLoader().getResourceAsStream("bootstrap.properties");
        try {
            Reader bootstrapReader = new InputStreamReader(bootstrapInstream, "UTF-8"); 
            bootstrapProperties.load(bootstrapReader);
            SPRING_FILE_ACTIVE = bootstrapProperties.getProperty("spring.profiles.active");

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try { bootstrapInstream.close();} catch (Exception e1) {}
        }
    }

    
    public static String getSpringFileActive() {
        return SPRING_FILE_ACTIVE;
    }
    
    public static void setSpringFileActive(String springFileActive) {
        SPRING_FILE_ACTIVE = springFileActive;
    }
}

如此,就可以通过PropertiesUtils.getSpringFileActive();来获取到bootstrap.properties里面的spring.profiles.active定义的值了。

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

推荐阅读更多精彩内容