[java]读取配置文件的几种方式

1、classload().getResourceAsStream(“name”) :从classPath下获取

        Properties properties = new Properties();
        InputStream is = demo.class.getClassLoader().getResourceAsStream("database.properties");

        try {
            System.out.println(is);
            properties.load(is);
        } catch (Exception e) {
            throw new IOException("config loading fail"+e);
        }

        String usernmae = properties.getProperty("username");

2、ResourceBundle.getBundle(“configname”) :必须是properties文件,必须在classpath目录下

        ResourceBundle resourceBundle = ResourceBundle.getBundle("database");
        Enumeration<String> keys = resourceBundle.getKeys();
        while(keys.hasMoreElements()){
            String key = keys.nextElement();
            String value = resourceBundle.getString(key);
            System.out.println(key+" : "+value);

如果是CN环境,使用ResourceBundle类,读取的是database_zh_CN.properties和database.properties和并集。如果两个配置文件都有一个属性,database_zh_CN.properties中的属性会覆盖database.properties配置文件中的属性。

**3、使用Spring自带的PropertiesLoaderUtils工具类 :**加载classpath目录下,yml和properties格式都可以

        Properties pro = null;

        pro = PropertiesLoaderUtils.loadAllProperties("application-dev.yml");
        Enumeration<?> enumeration = pro.propertyNames();
        
        /**
             遍历打印properties文件中key集合
        */
        while(enumeration.hasMoreElements()){
            String name = (String)enumeration.nextElement();
            String value = pro.getProperty(name);
            System.out.println(name+" : "+value);
        }

4、Environment获取配置文件:

package com.laty.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@RestController
@ComponentScan("com.laty")

public class TestController {
    
    @Autowired
    Environment env;

    @RequestMapping("/value")
    public Map<String,String> get(){
        
        HashMap map = new HashMap();
        map.put("url",env.getProperty("spring.datasource.url"));
        return map;

    }


    public static void main(String[] args) {
        SpringApplication.run(TestController.class,args);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值