在基于spring框架的B/S应用中,有时候需要在其他比如其他servlet等不属于spring容器范围中获取bean时,可用ApplicationContextAware来帮助我们。
废话不多说,直接上例子:
第一步,需要编写类实现ApplicationContextAware接口,如下面的AppUtil 类:
@Component
public class AppUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public AppUtil(){
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public static void setContext(ApplicationContext applicationContext){
AppUtil.applicationContext = applicationContext;
}
public static Object getBean(String paramString) {
return applicationContext.getBean(paramString);
}
}
第二步,实现一个特定的servlet,如
public class ApplicationContextLoaderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
AppUtil.setContext(
WebApplicationContextUtils.getWebApplicationContext(
config.getServletContext()));
}
}
第三步,将该servlet配置到web.xml
<servlet>
<servlet-name>ApplicationContextLoaderServlet</servlet-name>
<servlet-class>
com.easyfee.core.web.servlet.ApplicationContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
然后,童鞋们就可以再需要获得bean的地方进行使用了,如:
MyService myService = (MyService ) AppUtil
.getBean(“myService”);
希望这篇文章对大家有所帮助。