JBoss.org Community Documentation

11.5. Auto-wiring

Having to write large amounts of configuration information just to wire together sometimes trivial beans can often be frustrating. For this reason JBoss Microcontainer provides the ability to autowire beans. Auto-wiring means that a bean's properties or constructor/factory-method parameters are set by automatically searching for matching beans. The benefit is that you don't have to specify the names of the beans to inject yourself but the drawback is that this only works reliably for small environments. If you have an environment where more than one bean matches the property or parameter being set then it becomes unclear from the configuration information which one will be chosen during deployment.

To use auto-wiring you simply need to specify an @Inject annotation or <inject> element without a bean attribute for the parameter or property that you wish to set.


@Inject
public class Example(ThreadPool pool) {
    ...
}

<bean name="paramInj" class="com.acme.Example">
    <constructor>
        <parameter name="threadPool"><inject/></parameter>
    </constructor>
</bean> 

@Inject
public void setThreadPool(ThreadPool pool) {
    ...
}

<bean name="propInj" class="com.acme.Example">
    <property name="threadPool"><inject/></property>
</bean> 

By default the microcontainer will search for a bean whose class matches that of the parameter/property. However you can change this behaviour when auto-wiring properties so that the microcontainer searches for a bean whose name matches the property name. This is done using the type attribute of the <inject> element.


@Inject(type="ByName")
public void setThreadPool(ThreadPool pool) {
    ...
}

<bean name="propInj" class="com.acme.Example">
    <property name="threadPool"><inject type="ByName"/></property>
</bean> 

If no match is found then by default the deployment will fail but for certain properties it may be acceptable for injection to occur after deployment. In these cases you can specify that a property should be set using a callback mechanism whenever a suitable bean becomes available. This is done using the option attribute.


@Inject(type="ByName", option="Callback")
public void setThreadPool(ThreadPool pool) {
    ...
}

<bean name="propInj" class="com.acme.Example">
    <property name="threadPool"><inject type="ByName" option="Callback"/></property>
</bean> 

Sometimes you may want to prevent a bean from being injected automatically using auto-wiring. In these situations you can set its autowire-candidate attribute to false so that it's not included in the search for matching beans. This is not currently possible using annotations as there is no annotation to declare a bean.


<bean name="ignored" class="com.acme.Example" autowire-candidate="false" />