0

Usually, i'm accessing business objects (services) with @ManagedProperty in a main class annotated with @ManagedBean.

Here, i have a Servlet and i want to inject my business objects. The use of managedProperty doesn't work with the annotation @WebServlet.

When i use WebApplicationContext, it's working.

Does the use of WebApplicationContext is the clean way to do that or is there a cleaner method to do it ?

@WebServlet(urlPatterns ="/Graphic")
public class GraphicServlet extends HttpServlet {

    // Method 1 - This is not working ( the usual way in a ManagedBean)
    @ManagedProperty(value="#{participantBo}")
    private ParticipantBo participantBo; // getters and setters added

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Method 2 - This is working
        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        ParticipantBo participantBo = (ParticipantBo) springContext.getBean("participantBo");

        List<Participant> myParticipants = participantBo.findAllParticipant();

        for (Participant participant : myParticipants) {
            System.out.println(participant.getId_study());
        }
    }
}
ZheFrench
  • 1,164
  • 3
  • 22
  • 46

1 Answers1

0

Using WebApplicationContext is one of the ways to access the Spring web context from where you want. In fact, if you are able to reach Spring beans using @ManagedProperty, it means you have tied JSF and Spring frameworks in some way. @ManagedProperty should work only for JSF managed beans. However, being your servlet totally independent from the framework, accessing the Spring context this way is a choice.

See also:

Community
  • 1
  • 1
Aritz
  • 30,971
  • 16
  • 136
  • 217