• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best way to instantiate Spring context in a Servlet ?

 
Abhi Sal
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I need to instantiate a Spring applicationcontext in a Servlet. Is there any best way to do this ?

Also,

If the same ApplicationConext needs to be shared among many servlet, what would be the best way ?

Thanks and Regards,
Abhijit Salunkhe
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abhi Sal wrote:Hi,

I need to instantiate a Spring applicationcontext in a Servlet. Is there any best way to do this ?

Also,

If the same ApplicationConext needs to be shared among many servlet, what would be the best way ?

Thanks and Regards,
Abhijit Salunkhe


Best way is to use the ContextLoaderListener in your web.xml This will create an ApplicationContext for you when you deploy you war. This app context will be placed in your ServletContext for that app.

Then in your Servlets init method use

ApplicationContext context = ServletContextUtils.getRequiredWebApplicationContext(servletContext);

Now that code is not 100% compilable, you have to fill in the servletContext variable and my method call might be slightly wrong, but your IDE will tell you what methods are on the ServletContextUtils class.

Mark
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic