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