我做CDI的小测试项目.我的应用程序由EJB EAR和WAR组成,全部部署在Glassfish 4上.我使用Hibernate 4.3.4访问数据库.
我的目标是验证EJB(DAO)中的类可以接收到EntityManager的注入.
SessionBean EJB的模式不是很棒,但是我必须修改已经创建的应用程序,所以我没有太多的选择.
这是我的EJB代码:
@Named public class DAOTest implements Serializable { private static final long serialVersionUID = 1L; @PersistenceContext(unitName="CDI-ejb") private EntityManager em; public void test(){ //em.getClass(); } public EntityManager getEm() { return em; } public void setEm(EntityManager em) { this.em = em; } public DAOTest() { // TODO Auto-generated constructor stub } }
Service.java
@Stateless @LocalBean public class Service implements ServiceLocal { @Inject DAOTest test; /** * Default constructor. */ public Service() { // TODO Auto-generated constructor stub } @Override public void test() { test.test(); } }
和ServiceLocal.java
@Local public interface ServiceLocal { void test(); }
在我的战争中
@WebServlet("/Test") public class Test extends HttpServlet { private static final long serialVersionUID = 1L; @Inject private ServiceLocal service; /** * @see HttpServlet#HttpServlet() */ public Test() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response) */ protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { service.test(); } /** * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response) */ protected void doPost(HttpServletRequest request,IOException { // TODO Auto-generated method stub } }
我通过使用@ Stateless注释来对DAOTest进行了注释.一切都应该发生.所以CDI运作良好但是只要@命名它不想工作.
任何想法?
堆栈跟踪:
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [DAOTest] with qualifiers [@Default] at injection point [[BackedAnnotatedField] @Inject test.Service.test]
我的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"> </beans>
解决方法
默认情况下,Java EE 7具有隐式bean归档,即bean类需要将范围注释作为CDI bean进行发现.
@Named不是范围注释.尝试使用@Dependent来代替.
在CDI 1.1 / Java EE 7中不再需要beans.xml.如果你有一个,那么确切的版本和bean-discovery-mode有所不同.请参阅CDI 1.1规范的Bean archives部分.
因为你没有发布你的beans.xml,很难说这个文件是否是问题的一部分.