【问题标题】:Configure spring bean to be abstract or not in xml configuration through propeties通过属性在xml配置中配置spring bean是否抽象
【发布时间】:2013-10-29 11:44:49
【问题描述】:

我使用的是 Spring 3.0.5.RELEASE 版本,配置如下:

<bean id="advice.audit" class="com.mysite.SuperClass" abstract="${myproperty.from.file}"/>

我明白了:

${myproperty.from.file}' is not a valid value for 'boolean'

我怎样才能实现这种行为,或者也许有人会提供更好的从属性控制 bean 创建的想法。

升级到 Spring 3.1 不是一种选择,因此无法使用 Spring Profiles。

【问题讨论】:

  • 你能说明 myproperty.from.file 是在哪里定义的吗?你确定它在上下文中吗?
  • 属性在属性文件中定义,由Spring正确配置和加载。
  • 我有点困惑,让 bean 首先是抽象的还是不基于属性的。您是否只是尝试基于属性文件有条件地包含 bean,基本上就像 Spring Profiles 给您的一样?您能否使用该属性来确定要包含两个文件中的哪一个,其中一个具有 bean,而另一个没有?或者让您的 bean 具有“启用”或不具有“启用”属性,并且让 bean 始终存在但并不总是做任何事情。
  • 属性解析在 bean 初始化时完成。这要求属性可用。就个人而言,我在实现 BeanDefinitionRegistryPostProcessor 时遇到了问题。然后在读取属性之前初始化 bean,我得到了类似的错误。
  • Peter Cooper Jr.,我正在尝试有条件地包含或不包含 bean,就像 Spring 配置文件一样。对于 bean,我没有两种选择。我只想包括与否。 Bean 是第三方库,没有“启用”属性。

标签: java xml spring properties javabeans


【解决方案1】:

据我所知,abstract 属性并不意味着在运行时被属性值替换。 abstract 指示是否应将 &lt;bean&gt; 声明用作模板。例如,你可以有这个

<bean abstract="true">
    <property name="someField" value="some value" />
</bean>

如果abstract 的值在运行时以某种方式设置为false,Spring 将尝试为没有class 属性的&lt;bean&gt; 声明创建一个bean。它会创造什么?

另请注意,在 beans XSD 中,abstract 属性的类型为 xsd:boolean

<xsd:attribute name="abstract" type="xsd:boolean">
    <xsd:annotation>-<xsd:documentation>
        <![CDATA[ Is this bean "abstract", that is, not meant to be instantiated itself but rather just serving as parent for concrete child bean definitions? The default is "false". Specify "true" to tell the bean factory to not try to instantiate that particular bean in any case. Note: This attribute will not be inherited by child bean definitions. Hence, it needs to be specified per abstract bean definition. ]]>
    </xsd:documentation>
</xsd:annotation></xsd:attribute>

【讨论】:

  • 感谢您的回答,但这不是我们想要的行为。
  • @tvelykyy 我不知道您是如何绕过 XML 解析器的,但是您的 ApplicationContext 实例在尝试解析 xml 上下文文件时应该会立即失败。
猜你喜欢
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
  • 2014-12-25
  • 2020-11-24
  • 2017-03-12
  • 2011-09-24
  • 1970-01-01
相关资源
最近更新 更多