美文网首页
java通过PropertiesUtils工具类读取proper

java通过PropertiesUtils工具类读取proper

作者: haiyong6 | 来源:发表于2019-12-10 12:30 被阅读0次

    有些时候不是所有的类都能被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定义的值了。

    相关文章

      网友评论

          本文标题:java通过PropertiesUtils工具类读取proper

          本文链接:https://www.haomeiwen.com/subject/bazwgctx.html