Java Servlet Filters and scope of other Objects and Entity Manager
I am new to JSF, Filters and JPA, and am using NetBeans and Glassfish.
I have a JSF form which submits and in turn accesses an Object's Method which calls a Facade Object Method to do a DB query. The Facade Class uses an annotation to declare access to the EntityManager:
@PersistenceContext(unitName = "NAMEOFAPP")
private EntityManager em;
When I try and call the same Facade from a Filter Class (before or after chain.doFilter), the Facade Class and EntityManager work, however, if I instantiate my own class in the Filter Class and call a method which tries to access the Facade, it is not instantiated and I get a null exception when calling it.
So, how do I get my Class to access a Facade/EntityManager? I declare the Facade in the same way as in the Filter Class.
@EJB
private MyFacade myFacade;
Why do I have to New my cl开发者_JS百科ass when all of the others are already instantiated?
Thanks.
If using JavaEE 6, you'll be able to inject it using @Inject
- CDI provides this functionality.
If not, you'd have to look it up via JNDI.
You should not instantiate objects that are meant to be managed. If you do they will not get anything injected, including the entity manager.
Ok, with more than a hat-tip to Bozho, here's how I got it working. In the Filter Class I import:
import javax.inject.Inject;
and declare my Bean as follows:
@Inject
private MyBean myBean;
Now this Object is Injected. I also had to create an empty WEB-INF/beans.xml
<beans
xmlns="http://java.sun.com/xml/ns/javaee"
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/beans_1_0.xsd" />
Now it builds and runs without throwing an exception.
精彩评论