好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java 实现web项目启动加载properties属性文件

web项目启动加载properties属性文件

最近做项目,发现框架里面封装的项目一启动加载所有的properties文件挺方便好用的就自己动手写了一个.

1、首先要想在项目启动的时候就加载properties文件

就必需在web.xml中配置一个加载properties文件的监听器(listener);

?

1

2

3

4

5

<!-- Properties文件的监听器 -->

     < listener >

         < description >ServletContextListener</ description >

         < listener-class >com.lvqutour.utils.PropertyFileUtils</ listener-class >

     </ listener >

2、在web.xml文件中配置好了监听器之后

接下来我们就要实现监听器中的类com.lvqutour.utils.PropertyFileUtils,本人做的方法是将该类实现ServletContextListener接口,主要然后主要是重写里面的init方法,现在项目启动的时候就会加载application.local.properties文件了.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

 

/**

  * Created with IntelliJ IDEA.

  * Date: 2018/3/13 13:06

  * User: pc

  * Description:自定义properties文件读取工具类

  */

 

public class PropertyFileUtils implements ServletContextListener {

     private static Properties prop = new Properties();

     @Override

     public void contextInitialized(ServletContextEvent sce) {

         InputStream inputStream;

         try {

             inputStream = getClass().getResourceAsStream( "/XXX.properties" );

             if (inputStream != null ){

                 prop.load(inputStream);

             }

         } catch (IOException ex) {

             ex.printStackTrace();

         }

     }

 

     @Override

     public void contextDestroyed(ServletContextEvent sce) { 

     }

 

     public static String get(String params){

         return prop.getProperty(params);

     }

}

3、当然为了不让项目启动报错

我们必需在项目的resources中新建一个XXX.properties文件.

?

1

2

3

4

5

#微信支付相关

#密钥

KEY = longshengwenhuaweixiangmingWXpay

#连接超时时间(毫秒)

CONNECT_TIME_OUT = 10000

4、文件建好之后

我们这时要在其他类中获取该文件的路径,这样大家可以回过头来看一下在PropertyFileUtils类中有一个get()方法,这就是为给其他类获取文件中的属性提供的方法.其中params为.properties文件的键.

?

1

2

String key = PropertyFileUtils.get( "KEY" ); //密钥

int CONNECT_TIME_OUT = Integer.parseInt(PropertyFileUtils.get( "CONNECT_TIME_OUT" )); //连接超时时间

项目启动加载属性文件有对我们获取属性文件中的属性打非常方便不用每次都要去建流,然后去读属性文件.

PS:如果是在Controller里需要获取resource.properties里的值,可直接使用@value注解:

?

1

2

3

4

@Value ( "${KEY}" )

private String key; //密钥

@Value ( "${CONNECT_TIME_OUT}" )

private int CONNECT_TIME_OUT; //连接超时时间

出现加载java的properties配置文件空指针报错

刚开始把properties配置文件放在了与引用它的java文件并列的src下自定义的文件包下面, 结果一直都报空指针异常, 找不到路径

解决

后来移动到src根目录下面就ok了...应该是一种配置文件的规定吧...

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_36004521/article/details/79540499

查看更多关于java 实现web项目启动加载properties属性文件的详细内容...

  阅读:19次