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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章