一. 点睛
上面一篇Spring Boot核心(六):常规属性配置文章中使用@Value
注入每个配置在实际项目中会显得格外麻烦,因为我们的配置通常会是许多个,若使用上篇文章的方式则要使用@Value
注入很多次。
Spring
Boot
还提供了基于类型安全的属性配置方式,通过@ConfigurationProperties
将properties
属性和一个Bean
及其属性关联,从而实现类型安全的配置。
二. 示例
1. 新建Spring Boot项目
2.添加配置
在application.properties
上添加:
article.author=longjiazuo
article.name=spring boot
当然,我们也可以新建一个properties
文件,这就需要我们在@ConfigurationProperties
的属性locations
里指定properties
的位置,且需要在入口类上配置。
3. 创建类型安全的Bean
,代码如下所示:
package org.light4j.springboot.save.properties.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "article") // ①
public class ArticleSettings {
private String author;
private String name;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
代码解释:
① 通过
ConfigurationProperties
加载properties
文件内的配置,通过prefix
属性指定properties
的配置的前缀,通过locations
指定properties
文件的位置,例如:
@ConfigurationProperties(prefix = "article",locations={"classpath:config/article.properties"})
本例中,由于直接配置在application.properties
文件里面,所以不需要配置locations
属性。
4. 校验代码,修改HelloController
的代码如下所示:
package org.light4j.springboot.save.properties.controller;
import org.light4j.springboot.save.properties.config.ArticleSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private ArticleSettings articleSettings; //①
@RequestMapping("/")
public String hello() {
return "article name is "+ articleSettings.getName()+" and article author is "+articleSettings.getAuthor();
}
}
代码解释:
① 可以用
@Autowired
直接注入该配置
5. 运行
启动入口程序,访问http://localhost:8080,效果如下图所示:
三. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » Spring Boot核心(七):类型安全的属性配置