【发布时间】:2018-01-11 16:11:02
【问题描述】:
我需要根据在 maven 项目中使用 spring 框架传递的输入来读取属性文件。我的属性文件和应用程序上下文存在于 src/main/resources 下
我正在尝试使用环境 api 来注入属性文件。
代码:
@Component
@Configuration
@PropertySource("classpath:GeoFilter.properties")
public class CountryGeoFilter {
@Autowired
public Environment environment;
@Bean
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);”行不断收到空指针异常
我的 applicationContext.xml(src/main/resources)
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:GeoFilter.properties" />
</bean>
我还在 web.xml 中设置了 contextparam
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
我正在通过以下方式启动和调用函数
CountryGeoFilter objGeo = new CountryGeoFilter();
GeoFilterStore response = objGeo.getCountryGeoFilter(country);
return response;
我对春天很陌生,不知道我哪里出错了。任何帮助将不胜感激。
编辑:
我更新了启动代码以使用上下文
ApplicationContext context = new
AnnotationConfigApplicationContext(CountryGeoFilter.class);
CountryGeoFilter testGeoFilter =
context.getBean(CountryGeoFilter.class);
testGeoFilter.getCountryGeoFilter(country);
现在我得到以下异常
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'getCountryGeoFilter' defined in ..
Unsatisfied dependency expressed through method
'getCountryGeoFilter' parameter
0; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'java.lang.String' available: expected at
least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
【问题讨论】:
标签: java spring maven autowired properties-file