凡是被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。