Java Reference
In-Depth Information
@PersistenceContext
private EntityManager em;
The
@UserDatabase
qualifier can be used when you inject the object into another
bean,
RequestBean
, elsewhere in the application:
@Inject
@UserDatabase
EntityManager em;
...
page
273
shows how to use producer fields to generate an entity manager. You can use a
similar mechanism to inject
@Resource
,
@EJB
, or
@WebServiceRef
objects.
To minimize the reliance on resource injection, specify the producer field for the resource
in one place in the application, then inject the object wherever in the application you need
it.
Using a Disposer Method
You can use a producer method to generate an object that needs to be removed when its
work is completed. If you do, you need a corresponding
disposer method
, annotated with
a
@Disposes
annotation. For example, if you used a producer method instead of a pro-
ducer field to create the entity manager, you would create and close it as follows:
@PersistenceContext
private EntityManager em;
@Produces
@UserDatabase
public EntityManager create() {
return em;
}
public void close(@Disposes @UserDatabase EntityManager em) {
em.close();
}
The disposer method is called automatically when the context ends (in this case, at the end
of the conversation, because
RequestBean
has conversation scope), and the parameter
in the
close
method receives the object produced by the producer method,
create
.