在servlet中如何使用被Spring管理的service

2023-04-12


我的使用场景是SpringMvc+MyBatis,我总结了以下两种方式,三种方法。两种方式指的是采用注入方式和获取spring管理的bean。三种方法指的是,代理注入、硬编码获取bean和实现ApplicationContextAware接口获取bean。


第一种方式:采用注入方式。


编写一个代理类,代码如下:


@SuppressWarnings("serial")
public class ProxyServlet extends HttpServlet {

	@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		proxyServlet.service(req, res);
	}

	@Override
	public void init() throws ServletException {
		this.targetBean = getServletName();
		getServletBean();
		proxyServlet.init(getServletConfig());
	}

	private String targetBean;
	
	private Servlet proxyServlet;
	
	private void getServletBean(){
		WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());
		this.proxyServlet = (Servlet) wac.getBean(targetBean);
	}
}

然后编写需要注入service的servlet,代码如下:


@Component
public class MemcacheServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private GlobalCacheService globalCacheService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MemcacheServlet() {
        super();
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String flag = request.getParameter("flag");
		globalCacheService.test();
		if("q".equals(flag)){
			//取缓存
			String name = (String)globalCacheService.getCacheValue("_name1", Object.class);
			System.out.println("执行取缓存操作: " + name);
		}else if("f".equals(flag)){
			//放缓存
			String username = request.getParameter("username");
			globalCacheService.deleteCacheValue("_name1");
			if(!StringUtil.isBlank(username)){
				System.out.println("执行存缓存操作: " + username);
				globalCacheService.setCacheValue("_name1", username, 28800);
			}else{
				System.out.println("执行存缓存操作: " + username);
				globalCacheService.setCacheValue("_name1", "lzx", 28800);
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		this.doGet(request, response);
	}

}

最后在web.xml中配置如下:







	memcacheServlet
    com.hsis.core.servlet.web.ProxyServlet
  

	memcacheServlet
	*.to
  





第二种方式:获取spring管理的service,采用硬编码或者实现AplicationContextAware接口。


2.1 采用硬编码方法如下:



ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
或者
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
LzxService lzxService = (LzxService)wac.getBean("lzxService");

注:WebApplicationContext继承的ApplicationContext。


SpringContextUtil,代码如下:


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		applicationContext = applicationContext;
	}
	
	public static ApplicationContext getApplicationContext(){
		return applicationContext;
	}
	
	public static Object getBean(String name){
		return applicationContext.getBean(name);
	}
	
	public static  T getBean(String name, Class  requiredClass){
		return applicationContext.getBean(name, requiredClass);
	}

}

applicationContext.xml中配置一下:


在servlet中使用即可:


globalCacheService = (GlobalCacheService) SpringContextUtil.getBean("globalCacheService", GlobalCacheService.class);

实现Aware接口的类,初始化之后可以获取对应的资源,实现ApplicationContextAware接口的bean,初始化后被注入applicationContext实例。


如果使用ClassPathXmlApplicationContext、FileSystemClassPathXmlApplicationContext和FileSystemXmlApplicationContext等对象去加载Spring配置文件,会生成一个新的application对象,这样会产生冗余。


本文仅代表作者观点,版权归原创者所有,如需转载请在文中注明来源及作者名字。

免责声明:本文系转载编辑文章,仅作分享之用。如分享内容、图片侵犯到您的版权或非授权发布,请及时与我们联系进行审核处理或删除,您可以发送材料至邮箱:service@tojoy.com