SpringBoot YML 配置List<Bean>

时间:2025-04-05 08:56:40

 1.创建dto对象

@Data
@NoArgsConstructor
public class ActionDto {
    private String nameC;

    private String nameE;
}

配置

action:
  list:
    - nameC: asd
      nameE: asd1
    - nameC: qwe
      nameE: qwe1

注入

@Data
@Component
@ConfigurationProperties(prefix = "action")
public class ActionConfig {

    private List<ActionDto> list;

}

也可以采用map的方式装配

配置(两种方式都可以,选一种即可)

action1:
  map:
    asdasd: qwe
    zxczxc: ewq

action2: "{key1: 'value1', key2: 'value2'}"

注入

@Data
@Component
@ConfigurationProperties(prefix = "action1")
public class ActionConfig {

    private Map<String, String> map;
}
@Data
@Component
public class ActionConfig {

    @Value("#{${action2}}")
    private Map<String, String> maps;
}

大功告成

附两篇好文:

想详细了解的参考: /J080624/article/details/80269616

只想编程使用参考:/sdzhangshulong/article/details/80124900