It's possible define bean stereotypes via XML?

允我心安 提交于 2021-02-18 18:51:57

问题


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> 

?


回答1:


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




回答2:


It is not possible to dynamically add annotations to your classes. Simple answer to your question is: No, it is not possible to apply stereotype annotation via XML.

However stereotype annotation usually serve only as a marking annotations for AOP components (and component scan). You can define your own AOP behavior. Of course you won't be able to use any built in <xyz:annotation-driven \> shortcut declaration / configuration.



来源:https://stackoverflow.com/questions/24886846/its-possible-define-bean-stereotypes-via-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!