1 java dependency-injection glassfish java-ee cdi
我是CDI的新手.这是我的第一个例子,我正在尝试运行它.搜索过互联网后,我编写了以下代码:我想要注入的类
public class Temp {
public Temp(){
}
public String getMe(){
return "something";
}
}
Run Code Online (Sandbox Code Playgroud)
Servlet的
@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet {
@Inject
public Temp temp;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<body>");
out.println("<h1> Here it is"+temp.getMe()+ "</h1>");
out.println("</body>");
}
}
...
Run Code Online (Sandbox Code Playgroud)
但是我必须跟踪glassfish 4中的错误:
org.jboss.weld.exceptions.DeploymentException:WELD-001408在注入点[[BackedAnnotatedField] @Inject private xxx.example.NewServlet.temp]中带有限定符[@Default]的[Temp]类型的不满意依赖项
我究竟做错了什么?
Mas*_*dul 11
beans.xml内部不存在WEB-INF或文件需要更改bean-discovery-mode="annotated"为bean-discovery-mode="all".
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
Run Code Online (Sandbox Code Playgroud)
建议值" annotated"仅识别带注释的CDI托管bean.没有任何注释的Bean将被忽略.由于您的Temp课程不是CDIbean,因此建议不适用于您的情况.
要使用annotated,请使用@RequestScoped注释该类:
// Import only this RequestScoped
import javax.enterprise.context.RequestScoped;
@RequestScoped
public class Temp {
public Temp() { }
public String getMe() {
return "something";
}
}
Run Code Online (Sandbox Code Playgroud)
这RequestScoped会将你的Temp类转换为CDIbean并且可以使用 bean-discovery-mode="annotated".