Spring Boot 環境變數讀取 和 屬性物件的繫結 RelaxedPropertyResolver
阿新 • • 發佈:2019-02-03
凡是被Spring管理的類,實現介面 EnvironmentAware 重寫方法 setEnvironment 可以在工程啟動時,獲取到系統環境變數和application配置檔案中的變數。
如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<code class = "hljs java" > @Configuration
public
class MyWebAppConfigurer implements
EnvironmentAware
{
private
static final
Logger logger = LoggerFactory.getLogger(MyWebAppConfigurer. class );
private
RelaxedPropertyResolver propertyResolver;
@Value ( "${spring.datasource.url}" )
private
String myUrl;
/**
* 這個方法只是測試實現EnvironmentAware介面,讀取環境變數的方法。
*/
@Override
public
void setEnvironment(Environment env) {
logger.info(env.getProperty( "JAVA_HOME" ));
logger.info(myUrl);
String str = env.getProperty( "spring.datasource.url" );
logger.info(str);
propertyResolver =
new RelaxedPropertyResolver(env,
"spring.datasource." );
String url = propertyResolver.getProperty( "url" );
logger.info(url);
}
}</code>
|
@Controller @Service 等被Spring管理的類都支援,注意重寫的方法 setEnvironment 是在系統啟動的時候被執行。
或者如下Controller:
1 2 3 4 5 6 7 8 9 |
<code class = "hljs java" > @Controller
public
class PageController implements
EnvironmentAware{
@Override
public
void setEnvironment(Environment environment) {
String s = environment.getProperty( "JAVA_HOME" );
System.out.println(s);
}
}</code>
|
我們還可以通過@ConfigurationProperties 讀取application屬性配置檔案中的屬性。
?1 2 3 4 5 6 7 8 9 |
<code class = "hljs java" > @Configuration
@ConditionalOnClass (Mongo. class )
@EnableConfigurationProperties (MongoProperties. class )
public
class MongoAutoConfiguration {
@Autowired
private
MongoProperties properties;
}</code>
|
@ConditionOnClass表明該@Configuration僅僅在一定條件下才會被載入,這裡的條件是Mongo.class位於類路徑上 @EnableConfigurationProperties將Spring Boot的配置檔案(application.properties)中的spring.data.mongodb.*屬性對映為MongoProperties並注入到MongoAutoConfiguration中。 @ConditionalOnMissingBean說明Spring Boot僅僅在當前上下文中不存在Mongo物件時,才會例項化一個Bean。這個邏輯也體現了Spring
Boot的另外一個特性——自定義的Bean優先於框架的預設配置,我們如果顯式的在業務程式碼中定義了一個Mongo物件,那麼Spring Boot就不再建立。 ?
1 2 3 4 5 6 7 8 9 10 |
<code class = "hljs cs" > @ConfigurationProperties (prefix
= "spring.data.mongodb" )
public
class MongoProperties {
private
String host;
private
int port = DBPort.PORT;
private
String database;
// ... getters/ setters omitted
} </code>
|
它就是以spring.data.mongodb作為字首的屬性,然後通過名字直接對映為物件的屬性,同時還包含了一些預設值。如果不配置,那麼mongo.uri就是mongodb://localhost/test。