SpringBoot注解配置文件映射属性和实体类

382 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

使用@value注解配置文件自动映射到属性和实体类

配置文件加载可以使用两种方式

  1. Controller上面配置 @PropertySource(value = "classpath:config/testconfig.txt") classpath:config/testconfig.txt 这个是你的配置文件名称和路径
@RestController
@RequestMapping("/data/api")
@PropertySource(value = "classpath:config/testconfig.txt")
public class TestController {
  @Value("${configname}")
  String configname;
  @Value("${configtarget}")
  String configtarget;
  @RequestMapping("/testConfig")
  public ResponseData testConfig() {
    Map map = new HashMap() {{
      put("name",configname);
      put("target",configtarget);
    }};
    return ResponseData.buildSuccess(map,"success!");
  }
}
  1. 通过实体类映射配置文件
在实体类上加入@Component注解,让这个实体类可以被扫描到
使⽤ @PropertySource 注解指定配置文件位置
使⽤ @ConfigurationProperties 注解,设置相关属性
必须 通过注入IOC对象,才能在类中使⽤获取的配置文件值
@Autowired
private ResourceConfig resourceConfig;
示例
@ConfigurationProperties(prefix="testconfig")
@PropertySource(value = "classpath:config/testconfig.txt")
@Configuration
public class ResourceConfig {
  @Value("${configname}")
  String configname;
  @Value("${configtarget}")
  String configtarget;

  public String getConfigname() {
    return configname;
  }

  public void setConfigname(String configname) {
    this.configname = configname;
  }

  public String getConfigtarget() {
    return configtarget;
  }

  public void setConfigtarget(String configtarget) {
    this.configtarget = configtarget;
  }
}


@RestController
@RequestMapping("/data/api")
public class TestController {
  @Autowired
  private ResourceConfig resourceConfig;
  @RequestMapping("/testConfigByBean")
  public ResponseData testConfigByBean() {
    Map map = new HashMap() {{
      put("name",resourceConfig.getConfigname());
      put("target",resourceConfig.getConfigtarget());
    }};
    return ResponseData.buildSuccess(map,"success!");
  }
}