一、Java jdk读取Properties配置文件
1、通过jdk提供的java.util.Properties类
2、通过java.util.ResourceBundle类来读取
代码示例如下:
/**
* 方式一:通过jdk提供的java.util.Properties类。
* 这种方式需要properties文件的绝对路径
*/
public void readProperties() {
ClassLoader cl = PropertiesDemo. class .getClassLoader();
Properties p=new Properties();
InputStream in= null;
try {
// 可根据不同的方式来获取InputStream
//方式一:InputStream is=new FileInputStream(filePath); 这种方式需要properties文件的绝对路径
// in = new BufferedInputStream(new FileInputStream("D:\tanyang\study-demo\example\src\main\java\com\ty\demo\example\properties\test.properties"));
//方式三:通过PropertiesDemo.class.getClassLoader().getResourceAsStream(fileName)
// 这个方式要求文件在classpath下
//in = PropertiesDemo.class.getClassLoader().getResourceAsStream("test.properties");
if (cl != null ) {
in = cl.getResourceAsStream( "test.properties" );
} else {
in = ClassLoader.getSystemResourceAsStream( "test.properties" );
}
p.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(p.getProperty( "test.port" ).trim());
System.out.println(p.getProperty( "test.siteName" ).trim());
}
3、 maven 工程读取配置文件同上!
二、 spring 读取properties文件
1、通过xml方式加载properties文件
我们以Spring实例化dataSource为例,我们一般会在beans.xml文件中进行如下配置:
现在如果我们要改变dataSource,我们就得修改这些源代码,但是我们如果使用properties文件的话,只需要修改那里面的即可,就不管源代码的东西了。那么如何做呢?
Spring中有个标签,可以用来加载properties配置文件,location是配置文件的路径,我们现在在工程目录的src下新建一个conn.properties文件,里面写上上面dataSource的配置:
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc\:mysql\://localhost\:3306/shop
user=root
password=root
现在只需要在beans.xml中做如下修改即可:
标签也可以用下面的标签来代替,标签我们更加熟悉,可读性更强:
classpath:conn.properties
虽然看起来没有上面的简洁,但是更加清晰,建议使用后面的这种。但是这个只限于xml的方式,即在beans.xml中用${key}获取配置文件中的值value。
2、通过注解方式加载properties文件
我们来看一个例子:假如我们要在程序中获取某个文件的绝对路径,我们很自然会想到不能在程序中写死,那么我们也可以写在properties文件中。还是在src目录下新建一个public.properties文件,假设里面写了一条记录:
filePath=E\:\\web\\apache-tomcat-8.0.26\\webapps\\E_shop\\image
如果想在java代码中通过注解来获取这个filePath的话,首先得在beans.xml文件中配置一下注解的方式: