application.yaml
app-props:
uuidMap:
customerId: "af241470-7a1a-41b9-8861-33c37069b8f2"
resourceId: "213e8652-bb34-4709-bc4b-a3ad1587f619"
AppProps class:
@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;
}
}
MyClass:
@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);
}
}
Main class
@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();
}
}
When running the main class, the myClass.uuidMap is null and I got:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Map.get(Object)" because "uuidMap" is null at project1.MyClass.printInfo(MyClass.java:18) at project1.MainEntry.main(MainEntry.java:27)
How to fix this and get the member variable uuidMap populated with the data in application.yaml?
I noticed that there is a similar question @ConfigurationProperties prefix not working. But the difference is that I have the setter in AppProps, and The uuidMap is a map not just a String. Also, I got a warning Spring Boot Configuration Annotation Processor not configured in a red bar on my IntelliJ and I am not sure if that is related.
Thank you @M.Deinum. changing main class as below solved the problem