【发布时间】:2019-02-03 22:50:39
【问题描述】:
不确定是否有可能,因为属性命名空间是共享的,但我想知道如果来自同一类且仅通过 bean Id 不同的 bean 很少,如何使用来自特定配置文件的值进行 bean 属性注入。
例如,假设有一个类 Position
class Position{
int id;
String title;
}
每个位置都有一个带有值的属性文件:
Employee.properties
id=1
title=Employee
Director.properties
id=2
name=Director
XML 配置文件如下所示:
<beans xmlns=.......>
<bean id="employeeProp" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:Employee.properties"/>
</bean>
<bean id="directorProp" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:Director.properties"/>
</bean>
<bean id="employee" class="com.example.title" lazy-init="true">
<property name="id" value="#{employeeProp.id}"/>
<property name="title" value="#{employeeProp.title}"/>
</bean>
<bean id="director" class="com.example.title" lazy-init="true">
<property name="id" value="#{directorProp.id}"/>
<property name="title" value="#{directorProp.title}"/>
</bean>
</beans>
显然这不起作用,因为在 #{employeeProp.id} 中,我指的是 PropertyPlaceholderConfigurer 对象的 id 字段,而不是它从文件加载的数据。
Property or field 'id' cannot be found on object of type 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer' - maybe not public?
我曾考虑将配置作为内部 bean 传递给构造函数,但这会使类的逻辑不必要地复杂化。
在不修改类逻辑的情况下,如何根据不同文件中的值进行属性注入(或如果)?
【问题讨论】:
-
如果您在
Employee.properties中为“employee_id”等属性使用唯一名称而不是“id”,它应该可以工作。我只是怀疑这样做是否可行 -
我考虑了唯一名称,但这有点开销,因为这是另一个需要维护的完整性。在更大的范围内,它会导致不必要的问题。
-
在我看来,您基本上是在尝试使用属性文件创建数据库。如果这是真的,为什么不使用数据库?
-
重点是只使用属性