读取spring配置文件的方法(spring读取资源文件)
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>
如对本文有疑问,
点击进行留言回复!!
网友评论