Skip to content

Instantly share code, notes, and snippets.

@tknerr
Created December 13, 2013 22:08
Show Gist options
  • Save tknerr/7952238 to your computer and use it in GitHub Desktop.
Save tknerr/7952238 to your computer and use it in GitHub Desktop.
Using annotation-based Java EE Dependency Injection with selective override via ejb-jar.xml deployment descriptor with GlassFish 3.1.2.2 Files: * FooBean, which depends on a Bar * BarBean, which is the default implementation of a Bar * AlternativeBarBean is the Bar that should be used * ejb-jar.xml overrides the default Bar in FooBean with the A…
package com.acme;
/**
* alternative implementation of Bar, provided by com.acme, will be packaged alongside org.sample
*
* mappedName is required here, see http://stackoverflow.com/questions/7443306/javaee-6-javax-naming-namealreadyboundexception-use-rebind-to-override
*/
@Stateless(mappedName = "AlternativeBarBean")
public class AlternativeBarBean implements Bar {
...
}
package org.sample;
@Stateless
public class BarBean implements Bar {
...
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
this is the ejb-jar.xml of the com.acme package. It overrides a dependency defined in the org.sample package.
-->
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" version="3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
<enterprise-beans>
<!-- override FooBean's dependency on BarBean with AlternativeBarBean -->
<session>
<ejb-name>FooBean</ejb-name>
<ejb-local-ref>
<!-- this is the GlassFish generated JNDI name if no @EJB(name=...) is specified -->
<ejb-ref-name>org.sample.FooBean/bar</ejb-ref-name>
<!-- use this alternative implementation instead -->
<ejb-link>AlternativeBarBean</ejb-link>
</ejb-local-ref>
</session>
</enterprise-beans>
</ejb-jar>
package org.sample;
@Stateless
public class FooBean implements Foo {
@EJB
private Bar bar;
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment