Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Overview

This example demostrates demonstrates the use of the injection of environment entries using <b>Resource</b> @Resource annotation.

"EJB Core Contracts and Requirements" specification section 16.2.2"

...

  • "Environment entries may also be injected into the bean through bean methods that follow the
    naming conventions for JavaBeans properties. The annotation is applied to the set method for
    the property, which is the method that is called to inject the environment entry. The JavaBeans
    property name (not the method name) is used as the default JNDI name."

PurchaseOrder bean PurchaseOrderBean class shows use of @Resource annotation through a bean field.

Invoice bean InvoiceBean class shows the use of @Resource annotation through a setter method.

The source for this example can be checked out from svn:

...

maxLineItem field in PurchaseOrderBean class is annotated with @Resource annotation to inject a simple environment entry. Default value of10 is assigned. Deployer can modify the values of the environment entries at deploy time in deployment descriptor.

@Resource annotation of a field

No Format
    @Resource
    int maxLineItems = 10;

...

  • java:comp/env/org.apache.openejb.examples.resource.InvoiceBean/maxLineItems

@Resource annotation of a setter method

No Format
 
    @Resource
    public void setMaxLineItems(int maxLineItems) {
        this.maxLineItems = maxLineItems;
    }

...

Writing an JUnit test for this example is quite simple. We need just to write a setup method to create and initialize the InitialContext, and then write our test methods.

Test fixture

No Format
    protected void setUp() throws Exception {
        Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
        properties.setProperty("openejb.deployments.classpath.include", ".*resource-injection.*");

        initialContext = new InitialContext(properties);
    }

Test methods

No Format
    public void testAddLineItem() throws Exception {
        Invoice order = (Invoice) initialContext.lookup("InvoiceBeanBusinessRemote");
        assertNotNull(order);
        LineItem item = new LineItem("ABC-1", "Test Item");

        try {
            order.addLineItem(item);
        } catch (TooManyItemsException tmie) {
            fail("Test failed due to: " + tmie.getMessage());
        }
    }

...