spring @Configuration 搭配 @Value 從application配置檔案獲取相關屬性
spring @Configuration 搭配 @Value 從application配置檔案獲取相關屬性
application.yml 檔案示例
neo4j:
userName: neo4j
password: neo4j
host: 127.0.0.1
port: 7474
獲取屬性值
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
@Data
public class Neo4jConfig {
@Value("${neo4j.userName}")
private String userName;
@Value("${neo4j.password}")
private String password;
@Value("${neo4j.host}")
private String host;
@Value("${neo4j.port}")
private String port;
}
使用@Value
註解並配合${}
即可獲取application.yml 檔案裡面的屬性。這樣,當你需要使用上面那些屬性的時候只需注入Neo4jConfig
即可使用。
另外@Value
註解還可以配合#{}
使用,#{}
是spring 的el表示式,具有很強功能。比如獲取環境變數值:
@Value("#{systemProperties['user.home']}")
private String userHome;
這樣即可獲取就環境變數user.home
的值,關於其它的具體用法,請參考spring官方文件:
http://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions
參考
- http://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot
- http://www.baeldung.com/spring-yaml
- http://stackoverflow.com/questions/5322632/spring-expression-language-spel-with-value-dollar-vs-hash-vs
- http://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions
「其他文章」