在spring-boot中,@ applicationProperties(prefix=“app-props”)不起作用

qcbq4gxm  于 2023-10-16  发布在  Spring
关注(0)|答案(1)|浏览(95)

application.yaml

app-props:
  uuidMap:
    customerId: "af241470-7a1a-41b9-8861-33c37069b8f2"
    resourceId: "213e8652-bb34-4709-bc4b-a3ad1587f619"

AppProps类:

@Component
@ConfigurationProperties(prefix="app-props")
public class AppProps
{
  private Map<String, String> uuidMap;

  public Map<String, String> getUuidMap() {
    return uuidMap;
  }

  public void setUuidMap(Map<String, String> uuidMap) {
    this.uuidMap = uuidMap;
  }
}

我的班级:

@Component
public class MyClass
{
  @Autowired
  private AppProps appProps;

  public void printInfo()
  {
    Map<String, String> uuidMap = appProps.getUuidMap();
    String customerId = uuidMap.get("customerId");
    System.out.println(customerId);
  }
}

主类

@SpringBootApplication
@EnableConfigurationProperties
public class MainEntry  {
    public static void main(String[] args)
    {
      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainEntry.class);

      MyClass myClass = context.getBean(MyClass.class);
      myClass.printInfo();
      context.close();
    }
}

当运行主类时,myClass.uuidMap为null,我得到:
线程“main”java.lang.NullPointerException:无法调用“java.util.Map.get(Object)”,因为“uuidMap”在project1.MainEntry.java:27的project1.MyClass.printInfo(MyClass.java:18)中为空
如何解决这个问题并使用application.yaml中的数据填充成员变量uuidMap
我注意到,有一个类似的问题@ receivationProperties前缀不工作。但不同的是,我在AppProps中有setter,而uuidMap是一个map而不仅仅是一个String。此外,我在我的IntelliJ上的红色条中得到了一个警告Spring Boot Configuration Annotation Processor not configured,我不确定这是否相关。

fkaflof6

fkaflof61#

感谢您发送编修。改变主类如下解决了这个问题

public class MainEntry  {
    public static void main(String[] args)
    {
AnnotationConfigApplicationContext(MainEntry.class);
      ConfigurableApplicationContext context = SpringApplication.run(MainEntry.class, args);
      MyClass myClass = context.getBean(MyClass.class);
      myClass.printInfo();
      context.close();
    }

相关问题