Java中读取Properties配置文件的几种方式

一、Java jdk读取Properties配置文件

1、通过jdk提供的java.util.Properties类

2、通过java.util.ResourceBundle类来读取

代码示例如下:

    /**
     * 方式一:通过jdk提供的java.util.Properties类。
     * 这种方式需要properties文件的绝对路径
     */
    public  void readProperties()  {
        ClassLoader cl = PropertiesDemo. class .getClassLoader();
        Properties p=new Properties();
        InputStream in= null;
        try {
            // 可根据不同的方式来获取InputStream
            //方式一:InputStream is=new FileInputStream(filePath);  这种方式需要properties文件的绝对路径
            // in = new BufferedInputStream(new FileInputStream("D:\tanyang\study-demo\example\src\main\java\com\ty\demo\example\properties\test.properties"));
            
            //方式三:通过PropertiesDemo.class.getClassLoader().getResourceAsStream(fileName)
            //  这个方式要求文件在classpath下
            //in = PropertiesDemo.class.getClassLoader().getResourceAsStream("test.properties");
            if  (cl !=  null ) {
                in = cl.getResourceAsStream( "test.properties" );
            }  else {
                in = ClassLoader.getSystemResourceAsStream( "test.properties" );
            }
            p.load(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(p.getProperty( "test.port" ).trim());
        System.out.println(p.getProperty( "test.siteName" ).trim());
    }

3、 maven 工程读取配置文件同上!

二、 spring 读取properties文件

1、通过xml方式加载properties文件

我们以Spring实例化dataSource为例,我们一般会在beans.xml文件中进行如下配置:

 <!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->  
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
    <property name="driverClass" value="com.mysql.jdbc.Driver" />  
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop" />  
    <property name="user" value="root" />  
    <property name="password" value="root" />  
</bean>

现在如果我们要改变dataSource,我们就得修改这些源代码,但是我们如果使用properties文件的话,只需要修改那里面的即可,就不管源代码的东西了。那么如何做呢?
Spring中有个<context:property-placeholder location=""/>标签,可以用来加载properties配置文件,location是配置文件的路径,我们现在在工程目录的src下新建一个conn.properties文件,里面写上上面dataSource的配置:

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource  
driverClass=com.mysql.jdbc.Driver  
jdbcUrl=jdbc\:mysql\://localhost\:3306/shop  
user=root  
password=root  

现在只需要在beans.xml中做如下修改即可:

<context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 -->  
  
<!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->  
 <bean id="dataSource" class="${dataSource}"> <!-- 这些配置Spring在启动时会去conn.properties中找 -->  
    <property name="driverClass" value="${driverClass}" />  
    <property name="jdbcUrl" value="${jdbcUrl}" />  
    <property name="user" value="${user}" />  
    <property name="password" value="${password}" />  
 </bean>  

<context:property-placeholderlocation=""/>标签也可以用下面的<bean>标签来代替,<bean>标签我们更加熟悉,可读性更强:

<!-- 与上面的配置等价,下面的更容易理解 -->  
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 -->  
        <array>  
            <value>classpath:conn.properties</value>  
        </array>  
    </property>  
</bean>  

虽然看起来没有上面的<context:property-placeholder location=""/>简洁,但是更加清晰,建议使用后面的这种。但是这个只限于xml的方式,即在beans.xml中用${key}获取配置文件中的值value。

2、通过注解方式加载properties文件

我们来看一个例子:假如我们要在程序中获取某个文件的绝对路径,我们很自然会想到不能在程序中写死,那么我们也可以写在properties文件中。还是在src目录下新建一个public.properties文件,假设里面写了一条记录:

filePath=E\:\\web\\apache-tomcat-8.0.26\\webapps\\E_shop\\image

如果想在java代码中通过注解来获取这个filePath的话,首先得在beans.xml文件中配置一下注解的方式:

<!-- 第二种方式是使用注解的方式注入,主要用在java代码中使用注解注入properties文件中相应的value值 -->  
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
    <property name="locations"><!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样  
        <array>  
            <value>classpath:public.properties</value>  
        </array>  
    </property>  
</bean>

现在我们可以在java代码中使用注解来获取filePath的值了:

@Component("fileUpload")  
public class FileUploadUtil implements FileUpload {  
      
    private String filePath;  
    @Value("#{prop.filePath}")   
    //@Value表示去beans.xml文件中找id="prop"的bean,它是通过注解的方式读取properties配置文件的,然后去相应的配置文件中读取key=filePath的对应的value值  
    public void setFilePath(String filePath) {  
        System.out.println(filePath);  
        this.filePath = filePath;  
    }

注意要有set方法才能被注入进来,注解写在set方法上即可。在setFilePath方法中通过控制台打印filePath是为了在启动tomcat的时候,观察控制台有没有输出来,如果有,说明Spring在启动时,已经将filePath给加载好了

3. 利用spring 的PropertiesBeanDefinitionReader来读取属性文件

spring提供了有两种方式的bean definition解析器:PropertiesBeanDefinitionReader和XmLBeanDefinitionReader即属性文件格式的bean definition解析器和xml文件格式的bean definition解析器。
PropertiesBeanDefinitionReader 属性文件bean definition解析器
作用:一种简单的属性文件格式的bean definition解析器,提供以Map/Properties类型ResourceBundle类型定义的bean的注册方法。
我感觉该方法不是特别灵活,想了解可以查看这篇文章Spring设置与读取.properties配置文件的bean

4.spring boot 读取自定义roperties配置文件

实际开发中为了不破坏spring boot核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources/config目录下创建配置文件test.properties

内容如下:

test.port=8082
test.siteName=无忧2
创建管理配置的实体类
@PropertySource(value={"classpath:config/test.properties"})
@ConfigurationProperties(prefix = "test")
@Component
public class SpringReadProperties {

    private String port;
    private String siteName;

    public static void main(String[] args) {

    }
    public String getPort() {
        return port;
    }
    public void setPort(String port) {
        this.port = port;
    }
    public String getSiteName() {
        return siteName;
    }
    public void setSiteName(String siteName) {
        this.siteName = siteName;
    }
    @Override
    public String toString() {
        return "SpringReadProperties{" +
                "port='" + port + '\'' +
                ", siteName='" + siteName + '\'' +
                '}';
    }
}

创建测试Controller
@Controller
public class TestController {
    @Autowired
    private SpringReadProperties properties;
    @RequestMapping(value = "/test")
    public  void readProperties()  {
        System.out.println(properties.toString());

    }
}

注意:由于在SpringReadProperties类上加了注释@Component,所以可以直接在这里使用@Autowired来创建其实例对象。

访问:http://localhost:8080/test 时将得到

SpringReadProperties{port='8082', siteName='无忧2'}

三、利用第三方配置工具owner读取配置文件

1、添加maven 依赖

<dependency>
    <groupId>org.aeonbits.owner</groupId>
    <artifactId>owner</artifactId>
    <version>1.0.9</version>
</dependency>

2.在resources/config目录下创建配置文件test.properties

内容如下:

test.port=8082
test.siteName=无忧2

3.创建配置管理 ConfigCenter

@Config.Sources({"classpath:config/test.properties"})
public interface ConfigCenter extends Config {

ConfigCenter I = ConfigFactory.create(ConfigCenter.class);
@Key("test.port")
@DefaultValue("")
String getPort();

@Key("test.siteName")
@DefaultValue("无忧")
String getSiteName();

}

@Sources里面可以配置多个文件
配置文件之间还可以相互继承

4、测试

        ConfigCenter cfg = ConfigFactory.create(ConfigCenter.class);
        System.out.println(cfg.getPort());

        ConfigCenter instance = ConfigCache.getOrCreate(ConfigCenter.class);

        System.out.println(instance.getSiteName());

建议使用configCache获取,单例。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容