1. 程式人生 > >SpringBoot之自定義配置檔案

SpringBoot之自定義配置檔案

1.通過@Value註解使用自定義的配置檔案

@Value註解的工作原理(這一切都是在SpringBoot專案啟動時發生的)使用@Value獲取自定義的配置新建一個XX.properties檔案,在其中新增
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

為了方便,我直接用log4j.properties舉例子。

新建一個bean物件,裡面用到了@Value註解。注意!@Component是必須的,否則無法將這個類建立成bean物件並注入到Spring容器中。@PropertySource對應上圖propertySourceHolder,是用來宣告配置檔案位置,並把它注入到Spring容器中,這個註解在用到的配置檔案為application.properties時,是可以省略的,因為SpringBoot預設讀取application.properties檔案。
@Component
@PropertySource("classpath:log4j.properties") //如果在application.properties中,此註解可以省略
public class A {
	@Value("${log4j.appender.stdout}")
	private String datasource;
	
	public String hello() {
		System.out.println("攔截邏輯類被呼叫了");return datasource;
	}
}
通過@Autowired將A注入到Controller層中注意!由於@Value的值是注入的A的bean物件中,如果你用new A()來建立一個新的A物件,是無法獲得@Value的值的,所以要用@Autowired註解。
@Autowired
private A a;

@RequestMapping("/hello")
@ResponseBody
public String hello() {
	return a.hello();
}
完成!我們來看下輸出結果!

2.不通過@Value,而是直接以物件方式注入

同樣是log4j.properties檔案中,增加這段

log4j.logger.java.sql.Connection = DEBUG  
log4j.logger.java.sql.Statement = DEBUG  
log4j.logger.java.sql.PreparedStatement = DEBUG  
log4j.logger.java.sql.ResultSet = DEBUG

將A.java改為

@Component
@PropertySource("classpath:log4j.properties")  //宣告配置檔案位置,並將其注入到Spring容器中
@ConfigurationProperties(prefix="log4j.logger.java.sql")
public class A{
	//與字尾一一對應
	private String Connection;
	private String Statement;
	private String PreparedStatement;
	private String ResultSet;
	public String getConnection() {
		return Connection;
	}
	public void setConnection(String connection) {
		Connection = connection;
	}
	public String getStatement() {
		return Statement;
	}
	public void setStatement(String statement) {
		Statement = statement;
	}
	public String getPreparedStatement() {
		return PreparedStatement;
	}
	public void setPreparedStatement(String preparedStatement) {
		PreparedStatement = preparedStatement;
	}
	public String getResultSet() {
		return ResultSet;
	}
	public void setResultSet(String resultSet) {
		ResultSet = resultSet;
	}
	
}
再將A用@Autowired注入到controller層中
@Autowired
private A a;
@RequestMapping("/hello")
@ResponseBody
public String hello() {
	return a.getConnection()+" "+a.getPreparedStatement()+" "+a.getResultSet()+" "+a.getStatement();
}
完成!檢視列印結果為總結:最重要的就是要了解@Value工作原理圖,瞭解@PropertySource的左右,瞭解@ConfigurationProperties的作用。