【问题标题】:Read property files using @Autowired Null pointer exception使用@Autowired Null 指针异常读取属性文件
【发布时间】:2017-08-09 00:25:16
【问题描述】:

我需要根据在 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。

我对春天很陌生,不知道我哪里出错了。任何帮助将不胜感激。

【问题讨论】:

  • 假设你不需要在CountryGeoFilter之上的@Component

标签: java spring maven autowired property-files


【解决方案1】:

查看applicationContext.xml 的所有内容会很有帮助。

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

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

&lt;context:component-scan base-package="com.geo" /&gt;

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

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

此机制的其他示例是here

【讨论】:

  • 没错。我没有扫描包裹。谢谢
【解决方案2】:
  1. 如果 Environment 为空,即未正确注入,则可能发生 NPE。
  2. 还要确保您已在属性文件中转义了“:”。

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

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多