David Portabella
David Portabella

Reputation: 12710

init a spring bean from web.xml

I am updating an existing Java EE web application that uses Spring.

In my web.xml, there is a servlet defined as follows:

  <servlet>
    <display-name>My Example Servlet</display-name>
    <servlet-name>MyExampleServlet</servlet-name>
    <servlet-class>com.example.MyExampleServlet</servlet-class>
  </servlet>

now, in this class I need to add an @Autowite annotation:

class MyExampleServlet extends HttpServlet {
    @Autowired (required = true)
    MyExampleBean myExampleBean;

    [...]
}

the problem is that MyExampleBean is initialized by the Application Server (in my case, weblogic.servlet.internal.WebComponentContributor.getNewInstance...)

so, Spring is not aware of that, and Spring does not have a chance to wire "myExampleBean".

How to solve that? that is, how I need to modify web.xml or MyExampleServlet so that MyExampleServlet gets the reference to myExampleBean?

A possibility would be to add this init code inside MyExampleServlet, but it requires a reference to servletContext. How to get a reference to servletContext?

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
myExampleBean = (MyExampleBean) context.getBean("myExampleBean");

Upvotes: 1

Views: 1723

Answers (2)

David Portabella
David Portabella

Reputation: 12710

I see, HttpServlet/GenericServlet has a getServletContext() method, (and the application server calls first the servlet's init(ServletConfig config), and config contains a reference to servletContext).

See http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/GenericServlet.html

The code modified:

class MyExampleServlet extends HttpServlet {
    MyExampleBean myExampleBean;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        myExampleBean = (MyExampleBean) context.getBean("myExampleBean");
    }

    [...]
}

Upvotes: 2

storm_buster
storm_buster

Reputation: 7568

in your application context xml, you need something like

<bean id="myExampleBean" class="path/to/myExampleBean">

Upvotes: 0

Related Questions