读取spring配置文件的方法(spring读取资源文件)
程序员文章站
2024-02-22 12:55:28
1.spring配置文件
复制代码 代码如下:
<bean id="configproperties"
class="org.springframework.beans.factory.config.propertiesfactorybean">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
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);
package com.springdemo.resource;
<!-- 可以直接将一个文件路径赋值给resource类型的resource属性,spring会根据路径自动转换成对应的resource -->
<bean id="resourcebean" class="com.springdemo.resource.resourcebean" >
<property name="resource" value="classpath:/com/springdemo/resource/test.txt" ></property>
</bean>
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>
上一篇: asp.net源程序编译为dll文件并调用的实现过程
下一篇: Python元类应用之单例模式