Donnerstag, 3. Juli 2008

EJB3: Resource injection from the deployment descriptor

Enterprise Java Beans 3 (EJB3) cut back on the extensive use of a XML deployment descriptor. One useful application of such a descriptor is to “inject” values from this configuration file into member variables of a Bean object at deployment time.

Inside the bean use the @Resource annotation on the declaration of the variable you want to set:


@Resource(name="ExampleValue")
public String exampleValue = null;

Then in the deployment descriptor, inside the section of the Bean, create an <env-entry>:

<env-entry>
    <env-entry-name>ExampleValue</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>Test</env-entry-value>
    <injection-target>
        <injection-target-class>package.path.to.ExampleBean</injection-target-class>
        <injection-target-name>ExampleValue</injection-target-name>
    </injection-target>
</env-entry>

For the <env-entry-type> you can choose one of the java.lang. wrappers around Java’s primitive types or java.lang.String.

Note that the container injects the value after object construction, so it is not yet available in the constructor.

If the resource is not configured or the names mismatch, a warning will be logged, but the Bean will start anyway. So check that the value is set programmatically, too.

... comment