Buscar este blog

domingo, 8 de marzo de 2015

Export SpringBean as Servlet Context Attribute

Suppouse you have a bean callede "oneSpringBean" in your Root Application Context and you want to read it from a Servlet.

There are two solutions.
Simple way, when there is not context mess:

In the servlet you get the bean using WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getBean("oneSpringBean")


Complex way, when you have custom context scopes:


<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
 <property name="attributes">
  <map>
   <entry key="myAttribute" value-ref="oneSpringBean" />
  </map>
 </property>
</bean>

In the servlet you get the bean using getServletContext().getAttribute("myAttribute")

No hay comentarios:

Publicar un comentario