欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-03-30 09:08:21|栏目:JAVA代码|点击:

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>

上一篇:Java泛型extends及super区别实例解析

栏    目:JAVA代码

下一篇:详解Java中ArrayList类

本文标题:读取spring配置文件的方法(spring读取资源文件)

本文地址:http://www.codeinn.net/misctech/91082.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有