2020-03-10:因为项目在开发环境、测试环境和生产环境的部分数据有所区别,故分别有不同的yml文件,相关属性也要在yml中定义.然后尝试了很多方法去将yml文件中自定义的属性赋值给项目中一个类中字段,均失败.

解决方法:

一、查看别的项目中的使用方法发现,所有的自定义属性被抽成了一个新的yml文件,每个环境的都有一个对应的属性抽出来的yml文件.结构为下图,其中GlobalConstants为属性的yml文件:

springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_自定义属性


然后在对应的application-XX文件中引入该属性yml文件:

springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_set方法_02

profiles:
    include: devGlobalConstants

然后在需要使用该属性的类上面加上两个注解:

@Component // 表示由spring托管
@ConfigurationProperties(prefix = "globalonstants") // 配置属性, prefix为属性前缀, globalonstants如下图所示

springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_自定义属性_03


然后设置对应的属性,属性名称一定要和yml文件中一致, 提供对应的set方法.

springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_自定义属性_04


springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_set方法_05


其实上面的属性应使用private, 但是同事就是这么写的, 也就不改掉了.

这是第一种方式.

二、我今天采用的是第二种方式, 不使用额外的yml文件抽离自定义属性,而是直接在相应的application-XX文件中写入自定义属性,然后新建一个entity与之属性对应,使用的时候则@Autowire该entity,通过.get属性调用.

目录结构就如下,属性的yml都弃用.

springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_set方法_06


步骤如下:

(1).在yml文件中添加属性:

springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_自定义属性_07

(2).建一个实体,使用两个注解.然后对应的相同名称属性定义在实体类中, 提供对应的getset方法.

@Component
@ConfigurationProperties(prefix = "commonparam")
public class CommonParamEntity {

	private String p12FilePath;

	public String getP12FilePath() {
		return p12FilePath;
	}

	public void setP12FilePath(String p12FilePath) {
		this.p12FilePath = p12FilePath;
	}
}

(3).在想要用的地方引入,就OK了.

springboot yml配置文件配置mysql数据源 springboot加载yml配置文件_set方法_08

@Autowired
private CommonParamEntity commonParamEntity;

这两种方法解决从yml配置文件中加载自定义属性对的问题.其实还有一种使用environment的方式, 但是感觉上比较诡异,就没有采用.