使用@Autowired 空指针异常读取 属性 个文件

Read property files using @Autowired Null pointer exception

我需要根据在 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);
    }

我的applicationContext.xml(src/main/resources)

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

注意:我还有其他 类 和 属性 文件,我需要对其执行相同的操作,并在 applicationContext.xml.

中声明它们的 bean

我是 spring 的新手,不确定我哪里出错了。任何帮助将不胜感激。

看到全部 applicationContext.xml 会很有帮助。

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

您可能不是 "scanning" 包含 CountryGeoFilter 的包裹。如果 CountryGeoFilter 在包 com.geo 中,您的 spring 配置文件需要包含如下内容:

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

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

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

此机制的其他示例是 here

  1. 如果 Environment 为 null,即未正确注入,则可能会发生 NPE。
  2. 还要确保在 属性 文件中对“:”进行了转义。

检查工作示例:https://github.com/daggerok/spring-property-source-example