SpringBoot 系列:Spring Boot 配置文件与常用注解
Spring Boot 使用一个全局的配置文件,配置文件名是固定的 application,文件格式支持 yml 或者 properties,也即配置文件为 application.yml 或者 pplication.properties,凭个人喜好或者项目要求自行选取。
系列示例采用的是 yml 格式。
yml 格式语法为 k:(空格)v,空格不可省略,以缩进来控制层级关系,只要是左对齐的一列数据,都是同一个层级的。

这里我们配置了启动的端口为 10900,即覆盖默认 8080 端口。

当我们需要不同的环境配置时,例如开发、测试、生产可能配置项都不同,那我们可以使用 spring.profiles.active 来指定。其中{profile}对应你的环境标识,比如 application-dev.yml 表示开发环境,application-prod.yml 表示生产环境。

所以现在起作用的是 application-dev.yml 里面的配置,我们简单的在两个文件中设置了不同的 app.env 属性,至于怎么访问,我们稍后讲到。

更多的配置大家可以翻阅相关文档,例如可以设置 server.servlet.context-path 来更改项目访问路径,在之后的示例中,我们遇到某项配置再对其进行详细讲解。
二、常用注解
1.@Value
Spring Boot 为我们提供 @Value 注解快速访问配置文件属性,当然这个注解并不是 Spring Boot 专属,它只是扩展了 yml 文件的支持。
还记得刚刚的 app.env 属性吗?我们该怎么去获取属性值呢,这就需要用到 @value 注解了,还有我们现在在配置文件中,新增自定义属性 my.name。

新建一个 Controller,getName 获取 name 属性的值,而 @Value("${my.name}")则表示获取配置文件中 my 节点下 name 的值。

同理 getEnv 用来获取 app.env 的值。

通过请求地址,如我们期待的,我们可以获取到对应的值,并且 app.env 的值恰也是 application-dev.yml 种的配置,证明 spring.profiles.active 是有效的。

2.@ConfigurationProperties
当我们同一个节点下存在多个属性需要注入时,一个一个属性注入可能有些繁琐,所以此时我们可以使用 @ConfigurationProperties,它能将多个属性注入到对应的实体类中。

针对 my 节点下的 girl 节点,我们创建对应的实体,并使用 @ConfigurationProperties(prefix = "my.girl")表明我们需要注入的节点,属性即可注入。其中 @Component 声明为 bean 对象。

编写 getGirl 方法进行验证。

评论