h1. Via annotation
{code:title=Usable by EJB, Interceptor, Servlet, Filter, or Listener}
package org.superbiz.refs;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.sql.DataSource;
@Stateless
@Resource(name = "myFooDataSource", type = DataSource.class)
public class MyDataSourceRefBean implements MyBeanInterface {
@Resource
private DataSource myBarDataSource;
public void someBusinessMethod() throws Exception {
if (myBarDataSource == null) throw new NullPointerException("myBarDataSource not injected");
// Both can be looked up from JNDI as well
InitialContext context = new InitialContext();
DataSource fooDataSource = (DataSource) context.lookup("java:comp/env/myFooDataSource");
DataSource barDataSource = (DataSource) context.lookup("java:comp/env/org.superbiz.refs.MyDataSourceRefBean/myBarDataSource");
}
}
{code}
h1. Via xml
The above @Resource annotation usage is 100% equivalent to the following xml.
{code:xml|title=ejb-jar.xml or web.xml}
myFooDataSource
javax.sql.DataSource
org.superbiz.refs.MyDataSourceRefBean/myBarDataSource
javax.sql.DataSource
org.superbiz.refs.MyDataSourceRefBean
myBarDataSource
{code}