I am a very newbie in CDI. This is my FIRST example and I am trying to run it. Having searched the internet I wrote the following code:
Class that I want to be injected
public class Temp {
public Temp(){
}
public String getMe(){
return "something";
}
}
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>");
}
}
...
But I have to following error in glassfish 4:
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied
dependencies for type [Temp] with qualifiers [@Default] at injection
point [[BackedAnnotatedField] @Inject private
xxx.example.NewServlet.temp]
What am I doing wrong?
Best Answer
Either no
beans.xml
exists withinWEB-INF
or the file requires changingbean-discovery-mode="annotated"
tobean-discovery-mode="all"
.Explanation
The recommended value "
annotated
" only recognizes annotatedCDI
managed beans. Beans without any annotation are ignored. As yourTemp
class is notCDI
bean, so recommendation is not applicable in your case.Using bean-discovery-mode="annotated"
To work with
annotated
, annotate the class with @RequestScoped:This
RequestScoped
will convert yourTemp
class toCDI
bean and will be work withbean-discovery-mode="annotated"
.