【发布时间】:2013-05-23 10:55:35
【问题描述】:
我有一个扩展属性的类,用于存储一些专门的键名:
public class StorageConfiguration extends Properties {
private final String PROPERTY_NAME_1 = "property.key";
public String getProperty1() {
return this.getProperty(PROPERTY_NAME_1);
}
public void setProperty1(String property1) {
this.setProperty(PROPERTY_NAME_1, property1);
}
}
还有一个使用这些属性的类:
public class Storage {
StorageConfiguration storageConfiguration;
@Autowired
public void setStorageConfiguration(StorageConfiguration storageConfiguration) {
this.storageConfiguration = storageConfiguration;
}
public void init() {
// Initialize properties in this class using StorageConfiguration.
}
}
我的 Spring 设置为像这样初始化 Storage 和 StorageConfiguration:
<bean id="storage" class="com.k4rthik.labs.Storage" init-method="init">
<property name="storageConfiguration" ref="storageConfiguration" />
</bean>
<bean id="storageConfiguration"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="storageConfiguration">
<props>
<prop key="property.key">property_value</prop>
</props>
</property>
</bean>
我预期会发生的是 Spring 会通过将属性“property.key”设置为“property_value”来初始化 StorageConfiguration 对象。
但是我得到以下异常
org.springframework.beans.factory.BeanCreationException: 错误 创建在类路径资源中定义的名称为“storage”的bean [applicationContext.xml]:无法解析对 bean 的引用 设置 bean 属性时的“storageConfiguration” '授权配置';嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 创建在类路径中定义的名称为“authorizationConfig”的bean 资源 [applicationContext.xml]:设置属性值时出错; 嵌套异常是 org.springframework.beans.NotWritablePropertyException:无效 bean 类的属性“storageConfiguration” [org.springframework.beans.factory.config.PropertiesFactoryBean]:豆 属性“storageConfiguration”不可写或无效 设置方法。 setter的参数类型是否匹配return getter 的类型?
如您所见,我在 Storage 类中有一个用于 storageConfiguration 的自动装配设置器,所以我看不出这里有什么问题。
【问题讨论】:
-
您的
storageConfigurationbean 属于class="org.springframework.beans.factory.config.PropertiesFactoryBean"类。这是正确的吗? -
为什么要在 XML 配置中将
storageConfiguration注入到storage中并 用@Autowired注释setter?这不是多余的吗? -
如果你想要一个 setter,你不能使用 final 关键字。 final 表示该值不会在类中被修改。
标签: java spring properties