天天看點

springboot-加載自定義的properties檔案

在我們的開發中,有很多配置檔案是需要分開配置的,例如kafka.properties,amq.properties等,那這些自定義的配置檔案,怎麼加載到對應的類裡面了,下面就來說說這個問題。

在src/main/resources目錄下建立一個config檔案夾,用來存放我們的properties檔案。目錄結構如下:

springboot-加載自定義的properties檔案

user.properties配置檔案内容如下:

com.chhliu.springboot.author=xyy
com.chhliu.springboot.age=${com.chhliu.age}
com.chhliu.springboot.sex=woman
com.chhliu.springboot.time=20170123
com.chhliu.age=27
           

對應的配置類如下:

public class ConfigProperties {
	
	private String author;
	private int age;
	private String sex;
	private String time;
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getTime() {
		return time;
	}
	public void setTime(String time) {
		this.time = time;
	}
	@Override
	public String toString() {
		return "ConfigProperties [author=" + author + ", age=" + age + ", sex=" + sex + ", time=" + time + "]";
	}
}
           

我們怎麼來将配置檔案裡面對應的屬性注入到類中了,方法有二

1、過時方法

1.1 在ConfigProperties類上加上如下注解:

@ConfigurationProperties(locations="classpath:config/user.properties", prefix="com.chhliu.springboot")
           

其中locations屬性用來指定配置檔案的位置,prefix用來指定properties配置檔案中的key字首

1.2 在主類上加入配置支援

@EnableConfigurationProperties(ConfigProperties.class)
           

這樣就可以将properties配置檔案中的值注入到類中對應的屬性上去了,但是上面的這種方式已經被标注為過時了,在新的版本中是不可用的。

2、替代方法

1.1 在ConfigProperties類上加上如下注解:

@Component// 以元件的方式使用,使用的時候可以直接注入
@ConfigurationProperties(prefix="com.chhliu.springboot")// 用來指定properties配置檔案中的key字首
@PropertySource("classpath:config/user.properties")// 用來指定配置檔案的位置
           

1.2 關閉配置屬性的支援

這一步就是将主類上的@EnableConfigurationProperties這個注解注釋調,不讓springboot自動配置,使用我們的手動配置

3、測試結果

ConfigProperties [author=xyy, age=27, sex=woman, time=20170123]
           

從上面的測試結果,可以看出,配置生效了。

繼續閱讀