1.将配置文件的属性赋给实体类
当有很多配置属性 ,如果逐个地读取属性会非常麻烦 通常的做法会把这些属性名作为
变量名来 创建 JavaBean 变量,并将属性值赋给 JavaBean 变量的值。在配置文件 a pplication. y ml 中添加如下属性
my:
name
:
forezp
age:
12
创建
JavaBean
,其代码清单如下:
@ConfigurationProperties(prefix
="
my"
)
@Component
public
class
ConfigBean
{
private
String
name;
private
int
age
;
...
}
在上面的 代码中,在 ConfigBean 类上加 个注解@ ConfigurationProperties ,表明该类为配
置属性类 ,并加上配 置的 prefix ,例如本 案例的" my" 。另外需要在 Co nfigBean 类上加
@C
omponent
注解,
Spring Boot
启动时通过包扫描将该类作为
Bean 注入 IoC 容器中。
创建
Controller
,读取
ConfigBean
类的属性。在 Controller 类上,加
@E
nableConfigurationProperties
注解,并指明
onfigBean
类,其代码清单如下
@RestController
@EnableConfigurationProperties({ConfigBean.
class})
public
class
LucyController
{
@Au
tow
ired ConfigBean configBean;
@RequestMapping(value
=
"
/lucy"
)
public
String
miya()
{
return
configBean.getName()
+"-"+configBean.
getAge
()
;
}
2.源码分析读取配置文件信息
Spring Boot的启动类上有一个@SpringBootApplication注解,点进去
@EnableAutoConfiguration,翻译就是开启自动配置,其定义如下:
而这个注解也是一个派生注解,其中的关键功能由@Import提供,其导入的AutoConfigurationImportSelector的selectImports()方法通过SpringFactoriesLoader.loadFactoryNames()扫描所有具有META-INF/spring.factories的jar包。spring-boot-autoconfigure-x.x.x.x.jar里就有一个这样的spring.factories文件。
这个spring.factories文件也是一组一组的key=value的形式,其中一个key是EnableAutoConfiguration类的全类名,而它的value是一个xxxxAutoConfiguration的类名的列表,这些类名以逗号分隔,如下图所示:
以ServletWebServerFactoryAutoConfiguration配置类为例,解释一下全局配置文件中的属性如何生效,比如:server.port=8081,是如何生效的
在ServletWebServerFactoryAutoConfiguration类上,有一个@EnableConfigurationProperties注解:开启配置属性,而它后面的参数是一个ServerProperties类
在这个类上,我们看到了一个非常熟悉的注解:@ConfigurationProperties,它的作用就是从配置文件中绑定属性到对应的bean上,而@EnableConfigurationProperties负责导入这个已经绑定了属性的bean到spring容器中(见上面截图)。那么所有其他的和这个类相关的属性都可以在全局配置文件中定义,也就是说,真正“限制”我们可以在全局配置文件中配置哪些属性的类就是这些XxxxProperties类,它与配置文件中定义的prefix关键字开头的一组属性是唯一对应的。
至此,我们大致可以了解。在全局配置的属性如:server.port等,通过@ConfigurationProperties注解,绑定到对应的XxxxProperties配置实体类上封装为一个bean,然后再通过@EnableConfigurationProperties注解导入到Spring容器中。