Java代码读取properties文件

在开发Spring项目时,想做一个在java代码中读取properties文件的操作,查了一下,大多是是通过如下这两种方式来读取。

方法一:

<bean id="propertyConfigurer"  
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
      <property name="location">  
          <value>/WEB-INF/configs/aa.properties</value>  
      </property>  
</bean>  

方法二:

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
   <property name="locations"><!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样  
        <array>  
            <value>classpath:public.properties</value>  
        </array>  
    </property>  
</bean>  

但是,这两种方式都不符合要求。

方法一的properties中的值,只能通过${key}方式在xml配置文件中取值,而方法二只能通过注解 @Value(“#{key}”) 来取值。


而我的需求是通过java代码去读key值。所以,写了下面的读取properties文件的代码,通过getData获取值。

@Component
public class PropertiesRead {
    private String Tag = "PropertiesRead";
    @Resource
    private BusinessLogger Log;
    private Properties props;
    public Properties getInstance() throws IOException{
        if(props==null){//判断是否读取过,只读一次
            loadProps();//读取文件
        }
        return props;
    }

    private void loadProps() {
        Log.log(Tag, "开始读取properties文件内容");
        InputStream in = null;
        // 根目录是编译的class的目录
       in = PropertiesRead.class.getResourceAsStream("/msgpackage.properties");
       props = new Properties();
        try {
            props.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
       Log.log(Tag, "加载properties文件内容结束");

    }
    public String getData(String key) throws IOException{
       return getInstance().getProperty(key);
    }
}

调用类部分代码如下:

@RestController
public class BusinessCommonController {
    ...
    @Resource
    private PropertiesRead pr ;
    ...
    public Object getform(HttpSession session,@RequestParam("functionId") String functionId) throws Exception {
        String trancode = pr.getData("trancode");//取值
        Log.log(TAG, trancode);
        ...
        ...
        return formReturn;
    }
}

msgpackage.properties

trancode=5389

Log如下,初次访问会读取properties文件,再次访问直接取内存。

这里写图片描述
这里写图片描述
先分享到这,有问题欢迎各位支出,希望对大家有用。

猜你喜欢

转载自blog.csdn.net/h517604180/article/details/80197126