【问题标题】:It's possible define bean stereotypes via XML?可以通过 XML 定义 bean 原型吗?
【发布时间】:2014-09-13 05:48:42
【问题描述】:

有可能通过 XML 定义一个 bean 原型吗?比如:

<bean ... stereotype="org.springframework.stereotype.Service">
</bean>

或者,

<bean...>
    <stereotype class="mypackage.myStereotype" />
</bean> 

?

【问题讨论】:

  • 你想达到什么目的?
  • 嗨,安德烈。我正在尝试将 spring 原型提供的默认行为用于必须使用 xml 配置的项目中。我也想定义我的自定义原型并使用它们。

标签: xml spring stereotype


【解决方案1】:

可能最简单的解决方案是使用任意 Spring bean 元数据,如下所示:

<bean id="fooService" class="org.example.FooServiceImpl">
    <meta key="stereotype" value="mypackage.myStereotype" />
</bean>

spring-beans.xsd中meta元素的定义是:

<xsd:element name="meta" type="metaType">
    <xsd:annotation>
        <xsd:documentation><![CDATA[
Arbitrary metadata attached to a bean definition.
        ]]></xsd:documentation>
    </xsd:annotation>
</xsd:element>

<xsd:complexType name="metaType">
    <xsd:attribute name="key" type="xsd:string" use="required">
        <xsd:annotation>
            <xsd:documentation><![CDATA[
The key name of the metadata attribute being defined.
            ]]></xsd:documentation>
        </xsd:annotation>
    </xsd:attribute>
    <xsd:attribute name="value" type="xsd:string" use="required">
        <xsd:annotation>
            <xsd:documentation><![CDATA[
The value of the metadata attribute being defined (as a simple String).
            ]]></xsd:documentation>
        </xsd:annotation>
    </xsd:attribute>
</xsd:complexType>

然后您可以使用BeanDefinitionRegistry.getBeanDefinition(String)BeanDefinition.getAttribute(String name) 来读取bean 的构造型并对其进行处理。

另一种可能性是使用 spring bean schema authoring facilities。因此,您需要按照reference documentation example 中的说明实现BeanDefinitionDecorator

【讨论】:

    【解决方案2】:

    无法为您的类动态添加注释。对您的问题的简单回答是:不,不可能通过 XML 应用构造型注释。

    然而,原型注解通常只作为 AOP 组件(和 组件扫描)的标记注解。您可以定义自己的AOP behavior。当然,您将无法使用任何内置的&lt;xyz:annotation-driven \&gt; 快捷方式声明/配置。

    【讨论】:

    • 谢谢帕维尔,可以定义刻板印象并在没有注释的情况下使用它们吗?我可以标记一个类或一个bean是通过xml定型的吗?也许 标签在 bean 定义中?
    • @Helder 它的用例是什么?也许我可以为您提供替代方法。
    • Pavel,很抱歉之前没有回答你,也很抱歉我的英语。我们正在开发一个基于 XACML (oasis-open.org/committees/tc_home.php?wg_abbrev=xacml#XACML20) 的安全框架,并且我们基于存在于我们解决方案核心中的服务模型定义了一个面向服务的层结构。我们为每个服务模型设计了一个刻板印象,框架客户(基本上是我们组织中的其他产品/项目)可以使用它们来扩展或替换服务行为。
    • 服务模型的一个常见行为是将异常转换为服务客户端的已知异常。我们不能直接在核心实现(core-impl)上使用特定的spring注解,因为我们提供了对其他DI技术的支持(另一个jar会将core-impl与该技术绑定:spring、cdi等),因此,我们更喜欢使用 xml。因此,我们需要某种方式通过 xml 为 bean 或类型/类声明一个构造型。我们也不希望将实现行为的方面耦合到特定的包或类型,除了原型。提前致谢!
    • 在我看来,手动向一组 bean 添加构造型等同于定义 bean 列表。那么为什么不这样做呢?
    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2012-12-29
    • 2018-08-13
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    相关资源
    最近更新 更多