Autowiring in servlet

36,908

Solution 1

I followed the solution in the following link, and it works fine: Access Spring beans from a servlet in JBoss

public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

  public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
      config.getServletContext());
  }
}

Solution 2

Remove the @Configurable annotation from your servlet and add:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);

at the first line of your init() method.

Share:
36,908
Mahmoud Saleh
Author by

Mahmoud Saleh

I am Mahmoud Saleh an Enthusiastic Software Engineer, Computer Science Graduate, Experienced in developing J2EE applications, Currently developing with Spring,JSF,Primefaces,Hibernate,Filenet. Email: [email protected] Linkedin: https://www.linkedin.com/in/mahmoud-saleh-60465545? Upwork: http://www.upwork.com/o/profiles/users/_~012a6a88e04dd2c1ed/

Updated on March 01, 2020

Comments

  • Mahmoud Saleh
    Mahmoud Saleh over 4 years

    i want to use spring autowiring in servlet so here's my code:

    @Configurable
    public class ImageServlet extends HttpServlet {
    
       @Autowired
       private SystemPropertyDao systemPropertyDao;
    
       @Override
       public void init() throws ServletException {
    
    
       String imagePath = systemPropertyDao.findByID(StaticParam.CONTENT_FOLDER);
    
    }
    

    while the SystemPropertyDao is annotated with @Repository

    and my applicationContext.xml:

    <context:component-scan base-package="com.basepackage" />
    <mvc:annotation-driven />
    <context:annotation-config />
    <context:spring-configured/>
    

    web.xml:

      <servlet>
        <servlet-name>imageServlet</servlet-name>
        <servlet-class>com.xeno.basepackage.ImageServlet</servlet-class>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>imageServlet</servlet-name>
        <url-pattern>/myimages/*</url-pattern>
      </servlet-mapping>
    

    sometimes the autowiring works and sometimes it doesn't (the reference to the spring bean systemPropertyDao is null), can anyone please tell me if i am missing something?

  • hiway
    hiway over 10 years
    thanks very much. At first I use Resource annotation, it doesn't work, and Autowired works well.
  • Suryaprakash Pisay
    Suryaprakash Pisay almost 10 years
    Thank you very much, but why they specifically mentioned in jBoss?? Won't it work in weblogic??
  • Chucky
    Chucky about 9 years
    It will work in Weblogic and even in Tomcat ! This is only the title of the documentation: the solution is actually relying upon the standard servlet api and pure Spring classes.