Home > Books > Declaring Beans in the Bean Configuration File

Declaring Beans in the Bean Configuration File

    Each bean should provide a unique name or id and a fully qualified class name for the Spring IoC container to instantiate it. For each bean property of simple type (e.g., String and other primitive types), you can specify a <value> element for it. Spring will attempt to convert your value into the declaring type of this property. To configure a property via setter injection, you use the <property> element and specify the property name in its name attribute. A <property> requires that the bean contain a corresponding setter method.

    You can also configure bean properties via constructor injection by declaring them in the <constructor-arg> elements. There’s not a name attribute in <constructor-arg>, because constructor arguments are position-based.

    In the Spring IoC container, each bean’s name should be unique, although duplicate names are allowed for overriding bean declaration if more than one context is loaded. A bean’s name can be defined by the name attribute of the <bean> element. Actually, there’s a preferred way of identifying a bean: through the standard XML id attribute, whose purpose is to identify an element within an XML document. In this way, if your text editor is XML-aware, it can help to validate each bean’s uniqueness at design time.

    However, XML has restrictions on the characters that can appear in the XML id attribute. But usually, you won’t use those special characters in a bean name. Moreover, Spring allows you to specify multiple names, separated by commas, for a bean in the name attribute. But you can’t do so in the id attribute because commas are not allowed there.

    In fact, neither the bean name nor the bean ID is required for a bean. A bean that has no name defined is called an anonymous bean. You will usually create beans like this that serve only to interact with the Spring container itself, that you are sure you will only inject by type later on, or that you will nest, inline, in the declaration of an outer bean.

Categories: Books
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment