SpringBoot项目实战:四种读取properties文件的方式

这里说了四种方式可以把配置文件放到外部的。 
第一种是在jar包的同一目录下建一个config文件夹,然后把配置文件放到这个文件夹下; 
第二种是直接把配置文件放到jar包的同级目录; 
第三种在classpath下建一个config文件夹,然后把配置文件放进去; 
第四种是在classpath下直接放配置文件。

这四种方式的优先级是从一到四一次降低的。


注:前三种测试配置文件为springboot默认的application.properties文件



#######################方式一 有多种数据类型,其他方式不支持list 等类型#########################
com.zyd.type3=Springboot - @ConfigurationProperties
com.zyd.title3=使用@ConfigurationProperties获取配置文件
#map
com.zyd.login[username]=zhangdeshuai
com.zyd.login[password]=zhenshuai
com.zyd.login[callback]=http://www.flyat.cc
#list
com.zyd.urls[0]=http://ztool.cc
com.zyd.urls[1]=http://ztool.cc/format/js
com.zyd.urls[2]=http://ztool.cc/str2image
com.zyd.urls[3]=http://ztool.cc/json2Entity
com.zyd.urls[4]=http://ztool.cc/ua


#######################方式二#########################
com.zyd.type=Springboot - @Value
com.zyd.title=使用@Value获取配置文件


#######################方式三#########################
com.zyd.type2=Springboot - Environment
com.zyd.title2=使用Environment获取配置文件




一、@ConfigurationProperties方式


@Component 
@ConfigurationProperties(prefix = "com.zyd") 
// PropertySource默认取application.properties ,包括不同环境自动取对应的application-dev.properties 或者application-pro.properties  对yml也可以, 但是指定配置文件的话对yml 不支持
// @PropertySource(value = "config.properties") 
public class PropertiesConfig { 
public String type3; 
public String title3; 
public Map<String, String> login = new HashMap<String, String>(); 
public List<String> urls = new ArrayList<>(); 
public String getType3() { return type3; } 
public void setType3(String type3) { this.type3 = type3; } 
public String getTitle3() { 
try { 
return new String(title3.getBytes("ISO-8859-1"), "UTF-8"); 
} catch (UnsupportedEncodingException e) { 
e.printStackTrace(); 

return title3; 

public void setTitle3(String title3) { this.title3 = title3; } 
public Map<String, String> getLogin() { return login; } 
public void setLogin(Map<String, String> login) { this.login = login; } 
public List<String> getUrls() { return urls; } 
public void setUrls(List<String> urls) { this.urls = urls; } 
}


二、使用@Value注解方式
@RestController 
public class ConfigController { 
@Value("${com.zyd.type}") 
private String type; 
@Value("${com.zyd.title}") 
private String title;

@RequestMapping("/value") 
public Map<String, Object> value() throws UnsupportedEncodingException { 
Map<String, Object> map = new HashMap<String, Object>(); 
map.put("type", type); 
map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8")); 
return map; 
}

}


或者

@Component

指定外部配置文件:

@PropertySource({"classpath:config/my.properties","classpath:config/config.properties"})

或者

@PropertySource({"file:d:/config/my.properties","file:d:/config/config.properties"})

public class ConfigProperty { 
@Value("${com.zyd.type}") 
private String type; 
@Value("${com.zyd.title}") 
private String title;

get/set 方法
}
在controller 或者server 类中,使用
@Autowired
private ConfigProperty configProperty;


在方法中:
configProperty.getType() 获取


三、使用Environment
public class xxController { 
@Autowired 
private Environment env; 

@RequestMapping("/env") 
public Map<String, Object> env() throws UnsupportedEncodingException { 
Map<String, Object> map = new HashMap<String, Object>(); 
map.put("type", env.getProperty("com.zyd.type2")); 
map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8")); 
return map; 

}


四、使用PropertiesLoaderUtils
其实本人写了 PropertiesUtils ,调用外部的proerty 文件。代码如下:
@Component
public class PropertiesUtils {




    private static final Logger log = LoggerFactory.getLogger(PropertiesUtils.class);


    private static String profilepath = "/xxxxxx-#.properties";


    private static Properties props = new Properties();


    private static String env =  System.getProperty("spring.profiles.active","pro");
    public PropertiesUtils() {


        profilepath = profilepath.replace("#",env);
        log.info("-----------profilepath:{}", profilepath);
        InputStream is = null;
        try {
            if(env.equals("dev")){
                is = this.getClass().getResourceAsStream(profilepath);
            }else{
                String filePath = System.getProperty("user.dir")+profilepath;
                is = new BufferedInputStream(new FileInputStream(filePath));
            }


                props.load(is);
        } catch (Exception e) {
            log.error("PropertiesUtils--", e);
            return;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("PropertiesUtils-close-", e);
                }
            }
        }


    }


    public String getKeyValue(String key) {
        return props.getProperty(key);
    }




    /**
     *
     * @param keyname
     * @param keyvalue
     * @param isAppend :是否追加
     */
    public void writeProperties(String keyname, String keyvalue,boolean isAppend) {
        OutputStream fos = null;
        try {
            String path = "";
            if(env.equals("dev")){
                path =  this.getClass().getResource(profilepath).getPath();
            }else{
                path = System.getProperty("user.dir")+profilepath;
            }


            log.info("-writeProperties-path:{}",path);
            File file = new File(path);
            if(file.exists()){
                log.info("exist:" + file.getAbsolutePath());
            }else{
                log.info("{} not exist", path);


            }
            fos = new FileOutputStream(file);
            if(isAppend){
                String v = props.get(keyname).toString();
                keyvalue =v+","+keyvalue;
            }
            props.setProperty(keyname, keyvalue);


            props.store(fos, "Update '" + keyname + "' value");
        } catch (IOException e) {
            log.error("writeProperties:",e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                   log.error("writeProperties:",e);
                }


            }
        }
    }




    public void removeProperties(String keyname) {
        OutputStream fos = null;
        Properties properties = new Properties();


        try {
            String path = "";
            if(env.equals("dev")){
                path =  this.getClass().getResource(profilepath).getPath();
            }else{
                path = System.getProperty("user.dir")+profilepath;
            }
            File file = new File(path);
            if(file.exists()){
                log.info("exist:" + file.getAbsolutePath());
            }else{
                log.info("{} not exist", path);


            }
            fos = new FileOutputStream(file);
            Enumeration enumeration = props.propertyNames();
            while(enumeration.hasMoreElements() ){
                String key = (String)enumeration.nextElement();
                if(key.equals(keyname)){
                    continue;
                }
                properties.setProperty(key,props.getProperty(keyname));


            }


            properties.store(fos, "Update '" + keyname + "' value");
            writeProperties(keyname,"",false);
        } catch (IOException e) {
            log.error("writeProperties:",e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }
    }


}




当然贴出PropertiesLoaderUtils方法:
app-config.properties
#### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式
com.zyd.type=Springboot - Listeners
com.zyd.title=使用Listeners + PropertiesLoaderUtils获取配置文件
com.zyd.name=zyd
com.zyd.address=Beijing
com.zyd.company=in
PropertiesListener.java 用来初始化加载配置文件




public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {


    private String propertyFileName;


    public PropertiesListener(String propertyFileName) {
        this.propertyFileName = propertyFileName;
    }


    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        PropertiesListenerConfig.loadAllProperties(propertyFileName);
    }
}




public class PropertiesListenerConfig {
    public static Map<String, String> propertiesMap = new HashMap<>();


    private static void processProperties(Properties props) throws BeansException {
        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            try {
                // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
                propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (java.lang.Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static void loadAllProperties(String propertyFileName) {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
            processProperties(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }


    public static Map<String, String> getAllProperty() {
        return propertiesMap;
    }
}


@SpringBootApplication
@RestController
public class Applaction {
    
    @RequestMapping("/listener")
    public Map<String, Object> listener() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.putAll(PropertiesListenerConfig.getAllProperty());
        return map;
    }


    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Applaction.class);
        // 第四种方式:注册监听器
        application.addListeners(new PropertiesListener("app-config.properties"));
        application.run(args);
    }
}
 



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值