当前位置: 移动技术网 > IT编程>开发语言>Java > 读取spring配置文件的方法(spring读取资源文件)

读取spring配置文件的方法(spring读取资源文件)

2019年07月22日  | 移动技术网IT编程  | 我要评论

1.spring配置文件

复制代码 代码如下:

<bean id="configproperties"
         class="org.springframework.beans.factory.config.propertiesfactorybean">
          <property name="location" value="classpath:jdbc.properties"/>
    </bean>

2.读取属性方法

复制代码 代码如下:

applicationcontext c=new classpathxmlapplicationcontext("classpath:applicationcontext-datasource.xml");
properties p=(properties)c.getbean("configproperties");
system.out.println(p.getproperty("jdbcorcale.driverclassname"));


另一个朋友提供的读取spring配置文件的方法,也分享一下吧

直接读取方式:
复制代码 代码如下:

public void test() throws ioexception
 {
  resource resource = applicationcontextfactory.getapplicationcontext().getresource("classpath:com/springdemo/resource/test.txt");

  file file = resource.getfile();
  byte[] buffer =new byte[(int) file.length()];
  fileinputstream is =new fileinputstream(file);

  is.read(buffer, 0, buffer.length);

  is.close();
  string str = new string(buffer);
  system.out.println(str);

 }

通过spring配置方式读取:

复制代码 代码如下:

package com.springdemo.resource;

import org.springframework.core.io.resource;

public class resourcebean {

 private resource resource;

 public resource getresource() {
  return resource;
 }

 public void setresource(resource resource) {
  this.resource = resource;
 }
}

spring bean配置:

复制代码 代码如下:

 <!-- 可以直接将一个文件路径赋值给resource类型的resource属性,spring会根据路径自动转换成对应的resource -->
 <bean id="resourcebean" class="com.springdemo.resource.resourcebean" >
  <property name="resource" value="classpath:/com/springdemo/resource/test.txt" ></property>
 </bean>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网