我是 Spring 框架的新手,在尝试读取和使用文件中的属性时遇到一些问题。
总而言之,我想要做的是定义一个存储所有读取属性的类,使用这些属性执行某些操作的第二个类,以及使用结果的第三个类。
存储属性的类是:
@Configuration
public class PropertyClass {
@Value("${propertyName")
private Integer propertyName;
@Bean(name = "propertyName")
public Integer getPropertyName() {
return propertyName;
}
}
读取和使用这些属性的类:
@Component
public class PropertyReader {
private Integer myProperty;
@Autowire
@Qualifier("propertyName")
public void setMyProperty(
Integer myProperty) {
this.myProperty = myProperty;
}
public Integer getValue() {
//do something with myProperty
return result;
}
}
以及使用PropertyReader的类:
public class Utilizer {
private PropertyReader getPropertyReader() {
ApplicationContext context = new AnnotationConfigApplicationContext(PropertyReader.class);
PropertyReader reader = (BakerStorageClassConfigHelper)context.getBean("PropertyReader");
return reader;
}
}
我已将这些类注册为 application-config.xml 文件中的 bean:
<bean class="property.class.package.PropertyClass" depends-on="Environment" />
<bean class="reader.class.package.PropertyReader" />
我有一个environment.xml 文件,其中使用位置规则定义“Environment”bean 以查找属性文件。
现在,当我尝试获取“ApplicationContext”对象时,在“Utilizer”类中会引发异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'PropertyReader':
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire method: public void reader.class.package.PropertyReader.setMyProperty(java.lang.Integer);
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Integer]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
我尝试将 PropertyReader 类的注释更改为 @Repository 或 @Service,并尝试添加指定了 PropertyClass 包的 @ComponentScan,但这些都不适合我。
有人可以给我一些建议吗?
谢谢!
最佳答案
我不太明白为什么需要将 propertyName
声明为 Integer。
如果您需要的只是从文件中获取属性,那么您可以定义一个PropertiesFactoryBean 并将其 Autowiring 到您喜欢的任何其他bean。
假设您有一个包含值的 myValues.properties 文件:
key1=value1
key2=value2
定义 Bean:
@Bean(name = "myProperties")
public PropertiesFactoryBean detailQueriesFactoryBean()
{
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setLocation(new ClassPathResource("com/xxx/myValues.properties"));
return pfb;
}
现在,无论您需要什么,都可以:
@Autowired
@Qualifier("myProperties")
private Properties myValuesContainer;
public void myMethod(){
//this will get you "value1"
String value1 = myValuesContainer.getProperty("key1");
}
希望这对您有用。
--------------------针对您的情况----------------
如果它已经在应用程序上下文中,您可以使用@Value
直接在您的PropertyReader
中注入(inject)值并为其添加getter/setter。不需要 PropertyClass
,对吗?
或者您可以向 PropertyReader
添加 @PostConstruct 方法。在该方法内部,您可以从现有上下文中检索所需的值。
@PostContstruct
public void extractValues(){
//retrieve value from context and assign to whichever var.
}
关于java - Spring:使用从文件读取的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38701525/