I recently had this requirement where i had to enable Spring context to an HttpSevlet.
So this is how is started with
web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:/spring-bootstrap.xml classpath*:/spring-service.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>proxy</servlet-name> <servlet-class>com.proxy.servlet.HttpProxyServlet</servlet-class> <!-- <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>proxy</servlet-name> <url-pattern>/api/proxy/*</url-pattern> </servlet-mapping>
spring-bootstrap.xml
<beans profile="custom"> <!-- Can't use context:property-placeholder until Spring bug SPR-7765 is addressed --> <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer" p:location="file:#{systemProperties['app.conf']}" /> <!-- <context:property-placeholder location="classpath:/app.conf" /> --> </beans>
Note i am using spring profile to load properties to the application context
Now, in my ProxyServlet , i want to load values from the properties , so this is what I did
1 2 3 4 5 | @Value("${REALM_ID:}") private String ENV_REALM_ID; @Value("${service_base_url:}") private String ENV_SERVICE_BASE_URL; |
But as it turns out that the servlet did not load the values. By default the spring dependencies are not injected. So to do that i had to add the following
1 2 3 4 5 6 7 | @Override public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } |
1 | applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); |
The following post was useful in solving the prob
how-to-mage-java-servlet-managed-or-di-in-spring