您的位置:首页 > 编程语言 > Java开发

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

2016-12-15 23:07 495 查看
  首先真的很感谢这篇文章的作者,我在这次的项目中遇到了这个问题,看了很多网上的资料都没解决,直到看到这篇文章才解决,我用的是方法2.2。

 刚开始我把service设置成servlet的成员变量,不知道为什么不行,这种方式让这个servlet都无法使用,希望知道原因的朋友能告知。以至于我以为这篇文章也是不行,感到灰心丧气,两天都没解决这个问题。刚刚我再次尝试了一次,把service放到方法里,设置成局部变量,没想到竟然成功初始化了,而且成功调用后台取到值返回,让我差点“喜极而泣”,真的很开心,明天就可以接着把项目往下做了,具体内容参照以下。再次感谢作者!

-------------分割线------------------------

原文

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

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

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

Java代码  


@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,代码如下:

 

 

 

Java代码  


@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中配置如下:

Xml代码  


<servlet>  

    <servlet-name>memcacheServlet</servlet-name>  

    <servlet-class>com.hsis.core.servlet.web.ProxyServlet</servlet-class>  

  </servlet>  

<servlet-mapping>  

    <servlet-name>memcacheServlet</servlet-name>  

    <url-pattern>*.to</url-pattern>  

  </servlet-mapping>  

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

      2.1 采用硬编码方法如下:

     

Java代码  


ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  

或者  

WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);  

LzxService lzxService = (LzxService)wac.getBean("lzxService");  

    注:WebApplicationContext继承的ApplicationContext。

      2.2 采用实现AplicationContextAware接口方法,首先创建一个类SpringContextUtil,代码如下:

Java代码  


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> T getBean(String name, Class<T>  requiredClass){  

        return applicationContext.getBean(name, requiredClass);  

    }  

  

}  

 applicationContext.xml中配置一下:

 

 

 

Java代码  


<bean class=”SpringContextUtil” />  

 

     在servlet中使用即可:

Java代码  


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

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

      如果使用ClassPathXmlApplicationContext、FileSystemClassPathXmlApplicationContext和FileSystemXmlApplicationContext等对象去加载Spring配置文件,会生成一个新的application对象,这样会产生冗余。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: