Search code examples
javaspringmavenautowiredproperty-files

Read property files using @Autowired Null pointer exception


I need to read properties file based on the input passed using the spring framework in a maven project. My property files and application context are present under src/main/resources

I am trying to use the environment api to inject the properties file.

Code:

@Component
@Configuration
@PropertySource("classpath:GeoFilter.properties")
public class CountryGeoFilter {

    @Autowired
    public Environment environment;

    public GeoFilterStore getCountryGeoFilter(String country) throws 
CountryNotFoundException, IOException {

    GeoFilterStore countryFilterStore = new GeoFilterStore();

    String value = environment.getProperty(country);
    if (value == null) {
        throw CountryNotFoundException.getBuilder(country).build();
    }
    String[] seperateValues = value.split(":");

    countryFilterStore.setGameStore(isTrueValue(seperateValues[0]));

    countryFilterStore.setVideoStore(isTrueValue(seperateValues[1]));
    return countryFilterStore;
    }

    private boolean isTrueValue(String possibleTrueValue) {
        return !possibleTrueValue.equals("No") && 
        !possibleTrueValue.equals("N/A");
    }
}

But i keep getting null pointer exception at line "String value = environment.getProperty(country);"

I am invoking the function in the following manner

    try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");) {
        CountryGeoFilter objGeo = (CountryGeoFilter) context.getBean("geoFilter");
        GeoFilterStore responseStore = objGeo.getCountryGeoFilter(country);
    }

My applicationContext.xml(src/main/resources)

<bean id="geoFilter"
    class="com.package.CountryGeoFilter" />

Note: I have other classes and property files for which i need to do the same and have their beans declared in applicationContext.xml.

I am rather new to spring and not sure where i am going wrong. Any help would be appreciated.


Solution

  • It would be helpful to see all of applicationContext.xml.

    Without seeing applicationContext.xml, my answer is just a guess.

    It is possible that you are not "scanning" the package containing CountryGeoFilter. If CountryGeoFilter was in the package com.geo your spring configuration file would need to contain something like:

    <context:component-scan base-package="com.geo" />

    CountryGeoFilter has an @Component annotation. This annotation is meaningless unless Spring is aware of the class definition. To become aware of classes containing this annotation, Spring scans packages identified in the <context:component-scan/> element.

    When Spring scans this class definition, it will create a bean that is a singleton instance of this class. After it creates the instance, it will Autowire your Environment member.

    Additional examples of this mechanism are here.