MyBatis Java不同方式加载文件时的路径格式问题、Mybatis中加载.properties文件


public class LoadPropTest { public static void main(String[] args) throws IOException { //一、Properties的load方法加载文件输入流
        Properties props=new Properties(); File file1=new File("F:/Program Files/Java/IdeaProjects/MyBatisDemo/src/db.properties"); File file2=new File("src/db.properties"); File file3=new File("src/com/biguo/datasource/jdbc.properties"); //File file4=new File("jdbc.properties"); 报错,引起了我对相对路径的思考
        FileInputStream fileInputStream1=new FileInputStream(file3); FileInputStream fileInputStream2=new FileInputStream("src/com/biguo/datasource/jdbc.properties"); props.load(fileInputStream2); System.out.println(props.getProperty("url")); //二、通过类加载器 加载配置文件
        Properties p = new Properties(); InputStream in = LoadPropTest.class.getClassLoader().getResourceAsStream("com/biguo/datasource/jdbc.properties"); p.load(in); String name = p.getProperty("username"); System.out.println(name); //三、基名,文件必须是key=value的properties文件
        ResourceBundle bundle = ResourceBundle.getBundle("com/biguo/datasource/jdbc"); String driver = bundle.getString("username"); System.out.println(driver); } }

   如方式一所示,构造文件对象File时的路径,是以工程所在路径为基础的。所以指定的文件在“src”下,都需要添加“src”。

  而方式二和方式三,有个关键词“Resource”,这种情况下通常是以Package路径作为寻找路径,默认是以“src”文件夹为基础的。

  MyBatis中在mybatis-config.xml中加载jdbc.properties时,需要在Configuration的标签最前面添加如下元素:

<properties resource="com/biguo/datasource/jdbc.properties">
        <!-- 其中的属性就可以在整个配置文件中被用来替换需要动态配置的属性值。 -->
        <!--<property name="password" value="pigu20ing" />-->
</properties>

  这里也以resource属性指定加载路径。

  如果把resource指定为直接放在src文件下的db.properties文件,即resource="db.properties",也可以运行成功。

  关于.properties文件,Java中有对应类Properties。Properties类继承自Hashtable,是由一组key-value的集合,常用于为各种配置提供数据。

  以下是.properties文件的内容格式:

  • 注释内容由 # 或者! 开头
  • key,value之间用 = 或者 : 分隔。一行中既有=也有:时,第一个(或者=或者:)将作为key,value分隔符。
  • key 不能换行,value可以换行,换行符是\ ,且换行后的\t、空格都会忽略。
 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM