有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用@Autowired Null指针异常读取java属性文件

我需要根据在maven项目中使用spring框架传递的输入读取属性文件。我的属性文件和应用程序上下文位于src/main/resources下

我正在尝试使用环境api注入属性文件

代码:

@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");
    }
}

但我一直在“String value=environment.getProperty(country);”行中得到空指针异常

我以以下方式调用该函数

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

我的应用程序上下文。xml(src/main/resources)

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

注意:我还有其他类和属性文件,我需要对它们执行相同的操作,并在applicationContext中声明它们的bean。xml

我对春天还比较陌生,不知道我会错在哪里。任何帮助都将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    看到所有的applicationContext.xml会很有帮助

    没有看到applicationContext.xml,我的答案只是猜测

    您可能没有“扫描”包含CountryGeoFilter的包。如果CountryGeoFilter在包com.geo中,您的spring配置文件需要包含以下内容:

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

    CountryGeoFilter有一个@Component注释。除非Spring知道类定义,否则此注释没有意义。为了了解包含此注释的类,Spring扫描<context:component-scan/>元素中标识的包

    当Spring扫描这个类定义时,它将创建一个bean,它是这个类的一个单例实例。创建实例后,它将自动连接Environment成员

    这种机制的其他例子有here