Java Reference
In-Depth Information
For accessing multiple resources, use the corresponding grouping annotations
@javax.ejb.EJBs
and
@javax.annotation.Resources
. An example of injecting
dependency on an EJB into a bean's variable using the
@javax.ejb.EJB
annotation is
as follows:
import javax.ejb.EJB;
@Stateful
public class CatalogBean implements Catalog {
@EJB(beanName = "HelloBean")
private Hello hello;
public void helloFromCatalogBean() {
hello.hello();
}
}
In the preceding example, the
hello
variable is injected with the EJB
HelloBean
. The
type of the
hello
variable is
Hello
, which is the
HelloBean
is business interface that
it implements. Subsequently, we invoked the
hello()
method of the
HelloBean
.
A resource may also be injected into a setter method. If the resource type can be
determined from the parameter type, the resource type is not required to be specified
in the
@Resource
annotation. In the following code snippet, the setter method is
annotated with the
@Resource
annotation. In the setter method, the
dataSource
property is set to a JNDI resource of type
javax.sql.DataSource
with value as
catalogDB
.
private javax.sql.DataSource dataSource;
@Resource(name="catalogDB")
public void setDataSource (DataSource jndiResource) {
this.dataSource = jndiResource;
}
The setter method must follow the JavaBean conventions: the method name begins
with
set
, returns
void,
and has only one parameter. If the name of the resource is
the same as the property name, the resource name is not required to be specified in
the
@Resource
annotation. The JNDI name of the resource is of the format
class_name/catalogDB
,
class_name
being the class name.
private javax.sql.DataSource catalogDB;
@Resource
public void setCatalogDB (DataSource jndiResource) {
this.catalogDB = jndiResource;
}
Search WWH ::
Custom Search