我已经创建了一个运行良好的 spring 配置文件。
我的下一步是将用户配置属性与系统属性分开。
我已决定使用将由用户配置的 bean 创建额外的 xml 文件。
我在创建一些这样的逻辑 bean 时遇到了问题,这些 bean 封装了将由真实类 bean 使用的属性:
我在网上找到了一个以这种方式引用属性的选项:
用户配置文件
<bean id="numberGuess" class="x...">
<property name="randomNumber" value="5"/>
<!-- other properties -->
</bean>
系统配置文件
<import resource="UserConf.xml" />
<bean id="shapeGuess" class="y...">
<property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/>
<!-- other properties -->
</bean>
但我的问题是我需要 x...
类是合乎逻辑的,根本不应该被初始化,我不希望它泄露类层次结构的任何信息系统,因为它应该只在使用配置 xml 文件。
解决方案 1 是创建一个表示此属性的 Java 对象:
public class MyProps(...)
并在spring系统配置中添加一个bean parent:
<bean id="MyProps" class="path to MyProps"/>
在用户端将之前的 bean 更改为:
<bean id="numberGuess" parent="MyProps">
<property name="randomNumber" value="5"/>
<!-- other properties -->
</bean>
解决方案2是像Database.props一样使用平面配置文件,并使用工厂加载它。
解决方案 3 是使用 Spring Property Placeholder 配置从 XML 属性文件(例如 example )加载属性,但在这里我根本不知道如何获得更复杂的属性嵌套结构(属性需要用不同的逻辑名称分隔,例如 minNumber 将在 xAlgo 和 y algo 下定义)。
我不喜欢只创建新的 Java 类来处理这个问题或将我的用户配置移动到平面 Prop 文件(我需要 xml 结构),他们还有其他解决方案吗?
最佳答案
我会回答我自己的问题,因为它看起来是对我来说最好的解决方案(而且比建议的要简单得多)
我将使用 PropertiesFactoryBean 为我完成工作:
例如
用户配置文件
<bean id="numberGuess" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="randomNumber">3</prop>
<!-- other properties -->
</bean>
系统配置文件
<import resource="UserConf.xml" />
<bean id="shapeGuess" class="y...">
<property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/>
<!-- other properties -->
</bean>
关于java - Spring 从属性 bean 引用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14260328/