Defining bean in xml without class attribute

2019-04-10 04:03发布

问题:

I am a newbie to the world of Spring. In an interview, it was asked if we can create a bean in XML without specifying the class (that is, the bean would only have an id attribute). I did not have the answer to this. Please advise if we can create a bean in XML in Spring without specifying the class attribute and under which conditions we would normally do this.

回答1:

Spring documentation makes it quite clear:

<!--
    Each bean definition must specify the fully qualified name of the class,
    except if it pure serves as parent for child bean definitions.
-->
<!ATTLIST bean class CDATA #IMPLIED>

This section explains it in detail and provides useful examples.



回答2:

As described by Szymon, bean definition inheritance is one way. Schema based configuration is another way, see. For example, taken from Spring's documentation,

<!-- creates a java.util.List instance with the supplied values -->
<util:list id="emails">
    <value>pechorin@hero.org</value>
    <value>raskolnikov@slums.org</value>
    <value>stavrogin@gov.org</value>
    <value>porfiry@gov.org</value>
</util:list>