SpringBoot获得application.yml中数据的几种方式

Java
194
0
0
2024-02-27
标签   SpringBoot

源码下载

ChaiRongD/Demooo - Gitee.com

List集合

yml

myproject:
  whitelist:
    users:
      - zhangsan
      - lisi
      - 王五

properties

@Configuration
@ConfigurationProperties("myproject.whitelist")
@Data
public class WhiteListConfig {
    private List<String> users = new ArrayList<>();
}

controller

@Autowired
    private WhiteListConfig whiteListConfig;

    @GetMapping("/getWhileList")
    public Object getWhileList() {
        return whiteListConfig.getUsers();

    }

Array集合

yml

yourproject:
  whitearray:
    users:
      - zhangsan
      - lisi
      - 王五

properties

@Configuration
@ConfigurationProperties("yourproject.whitearray")
@Data
public class WhiteArrayConfig {


    private String[] users;


}

controller

@Autowired
private WhiteArrayConfig whiteArrayConfig;

@GetMapping("/getWhiteArray")
public Object getWhiteArray() {
    String[] users = whiteArrayConfig.getUsers();
    Arrays.stream(users).forEach(System.out::println);
    return whiteArrayConfig.getUsers();

}

配置映射为自定义Object

yml

student:
  name: zhangsan
  age: 11

properties

@Data
@Configuration
@ConfigurationProperties("student")
public class StudentProperties {


    private String name;
    private int age;
}

controller

@Autowired
    private StudentProperties studentProperties;

    @GetMapping("/studentProperties")
    public Object studentProperties() {
        return studentProperties.toString();

    }

配置映射为Map

yml

teachermap:
  teacher: {"cangjing": 90,"boduoye": 95}

properties

@Configuration
@ConfigurationProperties("teachermap")
@Data
public class TeacherMapConfig {


    private Map<String, Object> teacher = new HashMap<>();
}

controller

@Autowired
private TeacherMapConfig teacherMapConfig;

@GetMapping("/teacherMapConfig")
public Object teacherMapConfig() {
    teacherMapConfig.getTeacher().entrySet().forEach(System.out::println);
    return teacherMapConfig.getTeacher();

}