【问题标题】:How import in Bean Map value from application.yaml如何从 application.yaml 导入 Bean Map 值
【发布时间】:2021-03-25 09:41:07
【问题描述】:

这是我的应用程序 yaml:

employees:
         data:
              name surname: name surname
              name surname: name surname

这是我的课:

@Component
@ConfigurationProperties(prefix = "employees")
public class EmployeesMap {

private Map<String, String> data;

public void setData(Map<String, String> data) {
this.data = data;
   }

public Map<String, String> getData() {
 return data;
 }

@Override
public String toString() {
 System.out.println(data.toString());
 return data.toString();

 }
}

我在 Spring Boot 中启用了 @EnableConfigurationProperties(EmployeeMap.class)

我尝试使用:

  public ResponseEntity<Void> readConfig() {
    employeesMap.getEmployees();
    employeesMap.toString();

    return ResponseEntity.accepted().build();
  }

当我尝试调用 toString 时出现此错误:

java.lang.NullPointerException:无法调用“Object.toString()”,因为“this.employess”为空

【问题讨论】:

  • 你是如何在测试时创建 EmployeeMap 的对象的?如果它是自动接线的,那么它应该可以工作。
  • 是的,EmployeeMap 在我的测试中是@Autowired

标签: java spring-boot yaml


【解决方案1】:

要获取员工地图,您需要定义上一级的前缀。类似的东西

department:
      employees:
           name:abc
           salary:xxx

然后在 EmployeeMap 类中使用@ConfigurationProperties(prefix = "department")

【讨论】:

    猜你喜欢
    • 2021-11-14
    • 2019-02-04
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多