Configuration, ConfigurationProperties和EnableConfigurationProperties用法

由於以前一直對這些長得很像的註解只知其一;不知其二經常由於以爲確定是無論什麼錯確定是做者的坑(本身的鍋)。因而最近花了點時間去研究下具體使用方法,避免往後出錯。以前用的時候也常常去看csdn上的文章,基本都是千篇一概互相抄,至因而不是對的也沒人去指正。因而本身就寫下本身的感覺。java

@Configuration這個註解的主要做用是把使用該註解的類當作Bean來使用,用於配置Spring容器。 @ConfigurationProperties(prefix="xxxx") 用來獲取相同父標籤的元素的值。具體使用案例見下文。 **@EnableConfigurationProperties(xxx.class)**將配置好的類進行使用,在內填入參數類。app

具體案例:this

my:
servers:
	- dev.example.com
	- another.example.com
複製代碼

若是要獲取該yml文件的配置參數,咱們能夠經過這個方式來進行獲取spa

@ConfigurationProperties(prefix="my")
public class Config {

	private List<String> servers = new ArrayList<String>();

	public List<String> getServers() {
		return this.servers;
	}
}
複製代碼

在類中使用該註解,就能獲取相關屬性,該類須要有對應的gettersetter方法。 這樣就至關於具有了獲取yml文件中參數屬性的能力,可是並不表明能用,用的時候須要注意在類上面加入@Component註解,這樣Spring才能獲取到相關屬性。code

@Component
@ConfigurationProperties(prefix="acme")
public class AcmeProperties {

	// ... see the preceding example

}
複製代碼

另外一種使用的方法則是在須要使用這個配置類的類上方標註**@Configuration@EnableConfigurationProperties(xxx.class)**server

@Configuration
@EnableConfigurationProperties(XXXProperties.class)
public class MyConfiguration {
}
複製代碼
# application.yml
acme:
	remote-address: 192.168.1.1
	security:
	    username: admin
	    roles:
	        - USER
	        - ADMIN
複製代碼
@Service
public class MyService {

	private final AcmeProperties properties;

	@Autowired
	public MyService(AcmeProperties properties) {
	    this.properties = properties;
	}

 	//...

	@PostConstruct
	public void openConnection() {
		Server server = new Server(this.properties.getRemoteAddress());
		// ...
	}

}
複製代碼

上面這種方法也是能用從yaml文件中讀取到相對應的配置,而後再@Service層中,使用構造器的方式進行諸如,這樣就能調用相關屬性。我的寫的很爛,具體有問題請在評論下指出便可。rem

相關文章
相關標籤/搜索