user676567
user676567

Reputation: 1139

Accessing a Spring Bean from a Servlet

I have a Spring Bean defined in my applicationContext like:

<bean id="spaceReader" class="com.company.SpaceReader">
</bean>

I would like to be able to access this bean in my Application Servlet without having to use:

ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXT_LOCATION);
context.getBean("SpaceReader");

I've tried exporting it using the following:

<bean id="ContextExporter" class="org.springframework.web.context.support.ServletContextAttributeExporter">
    <property name="contextExporterAttributes">
        <map>
            <entry key="SpaceReaderKey">
            <ref local="spaceReader" />
        </entry>
        </map>
    </property>
</bean>

but when i inject it into the Servlet, it returns a Null value. Just wondering if there's something i'm missing when i export the Bean or when i try to access it in the Servlet?

Upvotes: 0

Views: 4296

Answers (1)

Maksym Demidas
Maksym Demidas

Reputation: 7817

You can inject dependencies using annotations even in servlet (there is a special SpringBeanAutowiringSupport helper class for this pourpose):

public class CustomServlet extends HttpServlet {

    @Autowired
    private ProductService productService;

   @Override
   public void init(ServletConfig config) throws ServletException {
      super.init(config);
      // inject productService dependency
      SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
   }

   ....

}

Upvotes: 5

Related Questions