JBoss.org Community Documentation

10.4. Creating bean aliases

By default each bean declared in the deployment descriptor has a unique name that is used to inject it into other beans or to provide a reference to clients at runtime. Sometimes however it is useful to define additional names or aliases. This can be done using the @Aliases annotation or <alias> XML element. System property replacement is used by default to change the value of the alias at runtime but you can disable this if required.

  • Defining extra bean names

    
    @Aliases({"MyAlias", "Test: ${test.name}"})
    public class SimpleBean {
        ...
    }
    
    <bean name="MyBean" class="org.acme.SimpleBean">
        <alias>MyAlias</alias>
        <alias>Test: ${test.name}</alias>
    </bean>
  • Disabling System property replacement

    
    @Aliases({"MyAlias", "Test: ${test.name}"} replace="false")
    public class SimpleBean {
        ...
    }
    
    <bean name="MyBean" class="org.acme.SimpleBean">
        <alias>MyAlias</alias>
        <alias replace="false">Test: ${test.name}</alias>
    </bean>

The type of an alias doesn't have to be a string. If you want to choose a different type then you can specify a class attribute in the <alias> XML element. At present you cannot do this using the @Aliases annotation.

  • Choosing a different alias type

    
    <bean name="MyBean" class="org.acme.SimpleBean">
        <alias class="java.lang.Integer">12345</alias> 
    </bean>

Sometimes you may wish to define an alias for a bean after it has been deployed. This can be done using the standalone <alias> element in the deployment descriptor. There is no equivalent annotation in this case as there is no sensible place to put it.

  • Defining a standalone alias

    
    <deployment name="FirstDeployment" xmlns="urn:jboss:bean-deployer:2.0">

        <bean name="Bean1" class="java.lang.Object"/>
        <bean name="Bean2" class="java.lang.Object"/>

    </deployment>

    <deployment name="SecondDeployment" xmlns="urn:jboss:bean-deployer:2.0">

        <bean name="Xyz1" class="java.lang.Object">
            <property name="locker1"><inject name="Lock1"></property>
            <property name="locker2"><inject name="Lock2"></property>
        </bean>

        <alias name="Bean1">Lock1</alias>
        <alias name="Bean2">Lock2</alias>

    </deployment> 

Note

Standalone aliases behave just like normal beans with respect to dependencies. Specifically they won't be deployed until the beans that they represent have been deployed first. Likewise when a bean is undeployed then any corresponding standalone aliases are undeployed first.

Furthermore if any beans depend on a standalone alias then they will not be deployed until the alias is deployed first. Similarly undeploying a standalone alias will cause all dependent beans to be undeployed, regardless of whether the bean that it represents remains deployed.