Invoke dao injected with spring management in servlet developed by JSP

  • 2021-12-19 06:28:58
  • OfStack

Invoke dao injected with spring management in servlet developed by JSP

We can inject dao into action with dependency injection of spring, and then we can directly call the methods in dao, but servlet is not managed by spring container, so dao class cannot be injected into servlet, so we cannot use the methods in dao.

Here's how to do it:


private UserDao userDao; 
   
    public void init() throws ServletException { 
    super.init(); 
     
    ServletContext servletContext = this.getServletContext(); 
     
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); 
     
    userDao = (UserDao)ctx.getBean("userDao"); 
  } 

Add the private variable UserDao to servlet, and then initialize 1 in init () method of servlet.


public UserDao getUserDao() { 
    return userDao; 
  } 
 
  public void setUserDao(UserDao userDao) { 
    this.userDao = userDao; 
  } 

Also add get set method. (There is no test if this is removed.)

You can call dao at will in servlet in the future, yeah!

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: