【问题标题】:Spring - use different properties file for each beanSpring - 为每个 bean 使用不同的属性文件
【发布时间】: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”,它应该可以工作。我只是怀疑这样做是否可行
  • 我考虑了唯一名称,但这有点开销,因为这是另一个需要维护的完整性。在更大的范围内,它会导致不必要的问题。
  • 在我看来,您基本上是在尝试使用属性文件创建数据库。如果这是真的,为什么不使用数据库?
  • 重点是只使用属性

标签: java spring


【解决方案1】:

原来你可以使用placeholderPrefix 属性来引用确切的配置占位符

所以生成的文件看起来像

<beans xmlns=.......>
<bean id="employeeProp" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:Employee.properties"/>
    <property name="placeholderPrefix" value="employee-"/>
</bean>

<bean id="directorProp" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:Director.properties"/>
    <property name="placeholderPrefix" value="director-"/>
</bean>

<bean id="employee" class="com.example.title" lazy-init="true">
    <property name="id" value="employee-id}"/>
    <property name="title" value="employee-title}"/>

</bean>

<bean id="director" class="com.example.title" lazy-init="true">
    <property name="id" value="director-id}"/>
    <property name="title" value="directorProp-title}"/>
</bean>

请注意,我没有使用默认值引用符号 ${name} 而是 name},因为由于某种原因,在使用前缀的情况下,前一个符号将 '${' 连接到值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多