Hi Folks,
I am back with a simple topic of how to load spring beans in
a servlet. The provision is already present without the need to access the
beans using WebApplicationContextUtils i.e. by implementing a factory class
something like below:
1: public class ServiceFactory {
2: public static RegistrationService getRegistrationService() {
3: RegistrationService registrationService = new RegistrationServiceImpl();
4: return registrationService;
5: }
6: }
And then in a servlet calling this service like below:
1: boolean saved = ServiceFactory.getRegistrationService().saveNewRegistration(user);
But as another alternative if I want to invoke the spring beans using WebApplicationContextUtils will be something like below:
1: RegistrationService registrationService;
2: @Override
3: public void init(ServletConfig config) throws ServletException {
4: super.init(config);
5: WebApplicationContext factory = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
6: registrationService = factory.getBean(RegistrationService.class);
7: }
And then use it like below:
1: boolean saved = registrationService.saveNewRegistration(user);
In order to achieve this we need to modify our web.xml like below:
1: <context-param>
2: <param-name>contextConfigLocation</param-name>
3: <param-value>/WEB-INF/spring-context.xml</param-value>
4: </context-param>
5: <context-param>
6: <param-name>log4jConfigLocation</param-name>
7: <param-value>/WEB-INF/log4j.xml</param-value>
8: </context-param>
9: <listener>
10: <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
11: </listener>
12: <listener>
13: <listener-class>
14: org.springframework.web.context.ContextLoaderListener
15: </listener-class>
16: </listener>
That’s all folks by having the above changes you should now be able to access spring beans in a servlet. Please get me in touch if you find any difficulty.
No comments:
Post a Comment