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

2023-12-25 18:53:02 浏览数 (1)

源码下载

ChaiRongD/Demooo - Gitee.com

List集合

yml

代码语言:javascript复制
myproject:
  whitelist:
    users:
      - zhangsan
      - lisi
      - 王五

properties

代码语言:javascript复制
@Configuration
@ConfigurationProperties("myproject.whitelist")
@Data
public class WhiteListConfig {
    private List<String> users = new ArrayList<>();
}

controller

代码语言:javascript复制
@Autowired
    private WhiteListConfig whiteListConfig;

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

    }

Array集合

yml

代码语言:javascript复制
yourproject:
  whitearray:
    users:
      - zhangsan
      - lisi
      - 王五

properties

代码语言:javascript复制
@Configuration
@ConfigurationProperties("yourproject.whitearray")
@Data
public class WhiteArrayConfig {


    private String[] users;


}

controller

代码语言:javascript复制
@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

代码语言:javascript复制
student:
  name: zhangsan
  age: 11

properties

代码语言:javascript复制
@Data
@Configuration
@ConfigurationProperties("student")
public class StudentProperties {


    private String name;
    private int age;
}

controller

代码语言:javascript复制
@Autowired
    private StudentProperties studentProperties;

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

    }

配置映射为Map

yml

代码语言:javascript复制
teachermap:
  teacher: {"cangjing": 90,"boduoye": 95}

properties

代码语言:javascript复制
@Configuration
@ConfigurationProperties("teachermap")
@Data
public class TeacherMapConfig {


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

controller

代码语言:javascript复制
@Autowired
private TeacherMapConfig teacherMapConfig;

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

}

0 人点赞