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

1. 属性单独映射


1. Controller上面配置
@PropertySource({"classpath:application.properties"})
2. 对要配置的属性添加注解
@Value("${web.file.path}")
private String filePath;
3. 接口测试
@GetMapping("/test/property-source")
public Object testPropertySource() {
    System.out.print("配置注入打印,文件路径为:" + filePath);
    return filePath;
}

2. 实体类配置文件(使用配置实体类)


1. 创建配置
  • application.properties 文件中添加一下内容

    # 测试实体类注入
    test.name = shadowolf
    test.domain = www.shadowolf.cn
    
2. 创建一个实体类 ServiceSettings.java
  • 两个属性 name 和 domain
  • 添加两个属性的get和set方法
3. 给类添加注解
  • 共有三个注解:@Component、@PropertySource、@ConfigurationProperties

  • @ConfigurationProperties 注解可以设置 key 的前缀

    @ConfigurationProperties(prefix = "test")
    
  • 详细代码

    // 服务器配置
    @Component
    @PropertySource({"classpath:application.properties"})
    // @ConfigurationProperties
    @ConfigurationProperties(prefix = "test")
    public class ServiceSettings {}
    
4. 添加@Value注解
@Value("${name}")
private String name;
@Value("${domain}")
private String domain;
  • 如果此处配置文件中的key与属性名意义对应,可以不加@Value注解,假如不一致,那么就需要加@Value注解进行映射
5. 使用配置实体类
  • 用到的地方进行注入
@Autowired
private ServiceSettings serviceSettings;

@GetMapping("/test/test-properties")
public Object testProperties() {
    System.out.println("serviceSettings: " + serviceSettings);
    return serviceSettings;
}

转载于:https://my.oschina.net/shadowolf/blog/1840999

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值