0

I am using Spring Boot and Java and my application.properties file looks like this right now:

 germany.berlin.zipcode.10245=Friedrichshain
 germany.berlin.zipcode.14193=Charlottenburg
 germany.berlin.zipcode.10247=Neukolln

I am using @ConfigurationProperties to extract the values assigned in the properties in my code. More specifically I want to be able to give the zipcode number(e.g. 10245) in a method and it should return the place (Friedrichshain in that case). What I have tried so far:

Properties Config class

@EnableConfigurationProperties(AddressConfig.class)
public class PropertiesConfig {

}

AddressConfig class

@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "germany.berlin")
public class AddressConfig {

    private Map<Integer, String> zipCode;

    public String getAreaForzipCode(int code) {
        return zipCode.get(code);
    }

}

But when I do:

getAreaForzipCode(10245)

I get a java.lang.NullPointerException: null

Does anyone know whats the proper way to do this? Thanks in advance

hispanicprogrammer
  • 367
  • 3
  • 6
  • 22
  • Does this answer your question? [How to inject a Map using the @Value Spring Annotation?](https://stackoverflow.com/questions/30691949/how-to-inject-a-map-using-the-value-spring-annotation) (I know it uses `@Value`, but the answer is the same I think.) – PMah Jul 01 '20 at 13:38
  • 1
    The annotation `@Configuration` is missing on your `PropertiesConfig` class. – adarsh Jul 01 '20 at 13:47
  • @adarsh didnt work – hispanicprogrammer Jul 01 '20 at 13:51
  • @hispanicprogrammer that's weird. The map should get initialized with values. In fact, I quickly did a set up on my machine and it works. What is the Spring Boot version you're using? I tried with `2.2.6.RELEASE`. If you don't have it already, try adding the `spring-boot-configuration-processor` dependency. – adarsh Jul 01 '20 at 14:09

1 Answers1

0

Configuration class valid usage example:

@Configuration
public class PropertiesConfig {

    @Bean
    MyComponent myComponent(final AddressConfig config) {
        final String area = config.getAreaForzipCode(10245); // Friedrichshain
        return new MyComponent(area);
    }
}