一、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文件中进行如下配置:
<!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop" />
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
现在如果我们要改变dataSource,我们就得修改这些源代码,但是我们如果使用properties文件的话,只需要修改那里面的即可,就不管源代码的东西了。那么如何做呢?
Spring中有个<context:property-placeholder location=""/>标签,可以用来加载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中做如下修改即可:
<context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 -->
<!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->
<bean id="dataSource" class="${dataSource}"> <!-- 这些配置Spring在启动时会去conn.properties中找 -->
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
</bean>
<context:property-placeholderlocation=""/>标签也可以用下面的<bean>标签来代替,<bean>标签我们更加熟悉,可读性更强:
<!-- 与上面的配置等价,下面的更容易理解 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 -->
<array>
<value>classpath:conn.properties</value>
</array>
</property>
</bean>
虽然看起来没有上面的<context:property-placeholder location=""/>简洁,但是更加清晰,建议使用后面的这种。但是这个只限于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文件中配置一下注解的方式:
<!-- 第二种方式是使用注解的方式注入,主要用在java代码中使用注解注入properties文件中相应的value值 -->
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations"><!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样
<array>
<value>classpath:public.properties</value>
</array>
</property>
</bean>
现在我们可以在java代码中使用注解来获取filePath的值了:
@Component("fileUpload")
public class FileUploadUtil implements FileUpload {
private String filePath;
@Value("#{prop.filePath}")
//@Value表示去beans.xml文件中找id="prop"的bean,它是通过注解的方式读取properties配置文件的,然后去相应的配置文件中读取key=filePath的对应的value值
public void setFilePath(String filePath) {
System.out.println(filePath);
this.filePath = filePath;
}
注意要有set方法才能被注入进来,注解写在set方法上即可。在setFilePath方法中通过控制台打印filePath是为了在启动tomcat的时候,观察控制台有没有输出来,如果有,说明Spring在启动时,已经将filePath给加载好了
3. 利用spring 的PropertiesBeanDefinitionReader来读取属性文件
spring提供了有两种方式的bean definition解析器:PropertiesBeanDefinitionReader和XmLBeanDefinitionReader即属性文件格式的bean definition解析器和xml文件格式的bean definition解析器。
PropertiesBeanDefinitionReader 属性文件bean definition解析器
作用:一种简单的属性文件格式的bean definition解析器,提供以Map/Properties类型ResourceBundle类型定义的bean的注册方法。
我感觉该方法不是特别灵活,想了解可以查看这篇文章Spring设置与读取.properties配置文件的bean
4.spring boot 读取自定义roperties配置文件
实际开发中为了不破坏spring boot核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources/config目录下创建配置文件test.properties
内容如下:
test.port=8082
test.siteName=无忧2
创建管理配置的实体类
@PropertySource(value={"classpath:config/test.properties"})
@ConfigurationProperties(prefix = "test")
@Component
public class SpringReadProperties {
private String port;
private String siteName;
public static void main(String[] args) {
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
@Override
public String toString() {
return "SpringReadProperties{" +
"port='" + port + '\'' +
", siteName='" + siteName + '\'' +
'}';
}
}
创建测试Controller
@Controller
public class TestController {
@Autowired
private SpringReadProperties properties;
@RequestMapping(value = "/test")
public void readProperties() {
System.out.println(properties.toString());
}
}
注意:由于在SpringReadProperties类上加了注释@Component,所以可以直接在这里使用@Autowired来创建其实例对象。
访问:http://localhost:8080/test 时将得到
SpringReadProperties{port='8082', siteName='无忧2'}
三、利用第三方配置工具owner读取配置文件
1、添加maven 依赖
<dependency>
<groupId>org.aeonbits.owner</groupId>
<artifactId>owner</artifactId>
<version>1.0.9</version>
</dependency>
2.在resources/config目录下创建配置文件test.properties
内容如下:
test.port=8082
test.siteName=无忧2
3.创建配置管理 ConfigCenter
@Config.Sources({"classpath:config/test.properties"})
public interface ConfigCenter extends Config {
ConfigCenter I = ConfigFactory.create(ConfigCenter.class);
@Key("test.port")
@DefaultValue("")
String getPort();
@Key("test.siteName")
@DefaultValue("无忧")
String getSiteName();
}
@Sources里面可以配置多个文件
配置文件之间还可以相互继承
4、测试
ConfigCenter cfg = ConfigFactory.create(ConfigCenter.class);
System.out.println(cfg.getPort());
ConfigCenter instance = ConfigCache.getOrCreate(ConfigCenter.class);
System.out.println(instance.getSiteName());
建议使用configCache获取,单例。