adam bien's blog

How to configure EJB 3.0 Session Beans using XML (sample) 📎

EJB 3.0 Session Beans can be configured using XML in different ways. You can use dependency injection, as well as programmatic lookup for this purpose. The dependency injection approach allows you the definition of default values in the bean class, which can be overwritten in the deployment descriptor (the XML-file).

All fields, which are going to be injected from XML should be marked with the @Resource tag. The default value can be already specified in the declaration.

 
@Stateless
public class ConfigurableBean implements Configurable {

   
    @Resource int someIntInjectedValue = 100;
    float someFloatValue = 2;
    
    @Resource SessionContext sessionContext;
    
    public int getSomeIntInjectedValue() {
        return this.someIntInjectedValue;
    }
    
    public float fetchSomeFloatValue(){
        return (Float)this.sessionContext.lookup("someFloatValue");
    }
 }

 The desired value has to be specified in the XML deployment descriptor.

<enterprise-beans>
    <session>
        <ejb-name>ConfigurableBean</ejb-name>
        <env-entry>
            <env-entry-name>someIntInjectedValue</env-entry-name>
            <env-entry-type>java.lang.Integer</env-entry-type>

            <env-entry-value>5</env-entry-value>

The <injection-target> tag has to be specified as well. It causes the actual injection. However, this is not DRY (the FQN of the bean appears in the XML again) and somehow annoying. However, we are going to optimize it in EJB 3.1...:-)


           <injection-target>

           <injection-target-class>
                    com.abien.javaee5patterns.configuration.ConfigurableBean
            </injection-target-class>
            <injection-target-name>someIntInjectedValue</injection-target-name>
            </injection-target>           
        </env-entry>
        <env-entry>
            <env-entry-name>someFloatValue</env-entry-name>
            <env-entry-type>java.lang.Float</env-entry-type>
            <env-entry-value>6</env-entry-value>
        </env-entry>
    </session>
</enterprise-beans>
</ejb-jar>

 The traditional "lookup" of environment entries can be still performed. However the injection of the SessionContext is needed for this purpose... I checked in the whole sample project into P4J5 (name: SessionBeanConfiguration).