JBoss.org Community Documentation

11.3. Using bean references

Injecting string-based properties or the return values of method calls into individual beans allows us to perform simple configurations. To create more complex configurations we need to wire beans together by injecting references using the @Inject annotation or <inject> element.


@Inject(bean = "Name1")
public void setSimpleBean(SimpleBean bean) {
    ...
} 

<bean name="SimpleBean" class="org.jboss.test.SimpleBean">
    <property name="simpleBean">
        <inject bean="Name1"/>
    </property>
</bean>

Bean injections can be used anywhere a string value is used but you must ensure that the type of bean being injected is compatible with the type of property being set. It is also possible to inject a property from one bean into another using the property attribute.


@Inject(bean = "Name1", property="age")
public void setAge(Integer age) {
    ...
} 

<bean name="SimpleBean" class="org.jboss.test.SimpleBean">
    <property name="age">
        <inject bean="Name1" property="age"/>
    </property>
</bean>

Although injection is simple to use it provides a very powerful way to create arbitrary relationships between POJO instances. The dependencies that are formed by these relationships are discussed in the next chapter 'Defining Dependencies'.

Note

Sometimes you may wish to declare a bean simply so that you can inject it into a single property. In this case you can replace the <inject> element with the bean declaration itself to reduce the amount of XML required. This is not possible using annotations as there is no annotation to declare a bean.


<bean name="SimpleBean" class="org.jboss.test.SimpleBean">
    <property name="testBean">
        <bean="TestBean" class="org.jboss.test.TestBean">
            <property name="age">25</property>
        </bean>
    </property>
</bean>