@PropertySource @ImportResource @Bean读取或替代配置文件
1、@PropertySource(了解)
我们知道系统配置文件的文件可以叫application.properties或者application.yml,但是由于企业项目比较庞大,需要配置内容比较多,我们可能把一个配置文件写成多个;
比如整个项目中有两个配置文件:
application.properties
db.properties
这种情况是会出现的,比如application.properties我们编写系统的配置信息(系统启动端口),db.properties我们编写数据库的配置信息;那这就有问题了,系统默认只加载application.properties或application.yml这俩中的一个,那db.properties文件如何加载,这就是我们@PropertySource注解的用处了
实现步骤
【1】 使用idea创建一个web工程
【2】在src/main/resource下创建db.properties
【3】编辑db.properties,填写如下内容
# 数据库账号
db.uname=root
# 数据库密码
db.pwd=123456
【4】创建一个类叫db.java
这里要注意db类和Application入口类的层次关系,前面说了,放错了会404
【5】编辑db.java,输入如下内容
这里有一点非常重要:使用PropertySource注解的同时,需要加上@ConfigurationProperties注解,因为需要它去指定前缀,我们在db.properties文件中编写的两个属性的前缀都是db;
package com.qs.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component //让spring容器创建DB类对象
@PropertySource(value = {
"classpath:db.properties"})
@ConfigurationProperties(prefix = "db")
public class DB {
private String uname;
private String pwd;
public String getUname() {
return uname;
}
public void