xmlspringstereotype

It's possible define bean stereotypes via XML?


It's possible, via XML, define a bean stereotype? Something as:

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

or,

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

?


Solution

  • Probably the easiest solution would be to use arbitrary spring bean metadata as follows:

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

    The definition of the meta element in spring-beans.xsd is:

    <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>
    

    You can then use BeanDefinitionRegistry.getBeanDefinition(String) and BeanDefinition.getAttribute(String name) to read the stereotype of the bean and process it.

    Another possibility would be using the spring bean schema authoring facilities. Therefore you would need to implement a BeanDefinitionDecorator as described in the reference documentation example.