Spring开发 - 通过实现ApplicationContextAware在Servlet中调用注解的Service

用过Spring MVC的人都知道,我们如何在Controller中注入Service,可以使用@Resource注解的方法。

有时候,实际在项目的过程中,我们需要在某个Servlet中使用Service, 但是由于Spring MVC中的Servlet都是由

DispatcherServlet统一管理的,因此,像Controller方式的注解方式注入在普通的Servlet中是行不通的。

本文介绍通过实现ApplicationContextAware的方法在你自己的Servlet中也可以很轻松地使用你的Service。

首先,你需要实现你的Spring上下文工具类,代码如下:

package com.tg.util.web;

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

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     * @param applicationContext
     * @throws BeansException
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取对象
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
     * @param name       bean注册名
     * @param requiredType 返回对象类型
     * @return Object 返回requiredType类型对象
     * @throws BeansException
     */
    public static Object getBean(String name, Class requiredType) throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 如果BeanFactory包含所给名称匹配的bean返回true
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    /**
     * 判断注册的bean是singleton还是prototype。
     * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     * @param name
     * @return boolean
     * @throws NoSuchBeanDefinitionException
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(name);
    }

    /**
     * @param name
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException
     */
    public static Class getType(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.getType(name);
    }

    /**
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.getAliases(name);
    }
}

 

第二步非常重要,你需要在你的Spring配置文件中加入你的工具类Bean的单例配置,代码如下:

 

<beans ...
  <bean id="SpringContextUtil "    class="com.tg.util.web.SpringContextUtil " scope="singleton" />
</beans>

 

最后一步就是使用了,代码如下:

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    ...
    GameInfoService service = (GameInfoService) SpringContextUtil.getBean("gameInfoService");
    List<GameInfo> games = service.getAll();
    ...
}

 

好了,一切大功告成!

 

时间: 2024-07-28 19:41:30

Spring开发 - 通过实现ApplicationContextAware在Servlet中调用注解的Service的相关文章

JavaWeb servlet中调用opencv类库的问题?

问题描述 JavaWeb servlet中调用opencv类库的问题? 我想在servlet 中调用的opencv , 由于我已经通过Java的main方法成功配置并且已经调用成功啦,但是用在servlet里面通过浏览器访问servlet就会报加载类库失败的错误 , 错误如下: java.lang.UnsatisfiedLinkError: no opencv_java247 in java.library.path java.lang.ClassLoader.loadLibrary(Class

Servlet中监听器介绍

概述:Servlet监听器用于监听一些重要事件的发生,监听器对象可以在事情发生前.发生后可以做一些必要的处理.接口:目前Servlet2.4和JSP2.0总共有8个监听器接口和6个Event类,其中HttpSessionAttributeListener与HttpSessionBindingListener皆使用HttpSessionBindingEvent;HttpSessionListener和HttpSessionActivationListener则都使用HttpSessionEvent

javaservlet中调用javaBean

问题描述 急,急,急!请高手指点指点啊,十分感谢!(如何在servlet中调用bean,);<编译servlet时提示找不到BaseDao?>bean程序如下:packagetest;importjava.sql.*;importjavax.naming.Context;importjavax.naming.InitialContext;publicclassBaseDao{Connectioncon;Statementsmt;ResultSetrs;publicConnectiongetCo

eclipse + JBoss 5 + EJB3开发指南(13):在Servlet中访问应用程序管制EntityManager对象

本文为原创,如需转载,请注明作者和出处,谢谢! 上一篇:eclipse + JBoss 5 + EJB3开发指南(12):使用命名查询执行JPQL      在前面的文章中使用的都是容器管制的EntityManager对象.这类EntityManager对象是由EJB容器创建的,在这种情况下,EntityManager对象的生命周期完全由EJB容器来管理.在SessionBean中可以使用如下的代码来通知EJB容器创建EntityManager对象: @PersistenceContext(un

如何使用spring将service层注入到servlet中去(how to use Spring to inject ur service layer into the servlet )

In a typical struts+spring framework, we know how to inject our "service" into the "action". But sometime we have to use the "servlet". I mean the real servlet, not the struts's action-servlet! For example: We have a servlet

EJB3开发(13):在Servlet中访问应用程序管制EntityManager对象

本文为原创,如需转载,请注明作者和出处,谢谢!      在前面的文章中使用的都是容器管制的EntityManager对象.这类EntityManager对象是由EJB容器创建的,在这种情况下, EntityManager对象的生命周期完全由EJB容器来管理.在SessionBean中可以使用如下的代码来通知EJB容器创建 EntityManager对象: Code: @PersistenceContext(unitName="myentity")   protected Entity

javaweb开发工具有哪些?j2ee中那些技术规范较为主流?

问题描述 javaweb开发工具有哪些?j2ee中那些技术规范较为主流? 目前已下载jdk,tomcat,Dreamweaver,myeclipse.技术规范打算先学servlet,jsp. 解决方案 Eclipse IDE for Java EE Developers 254 MB.在eclipse官方下载http://download.eclipse.org/或者myeclipse.冉要Licence破解,相对好用一点.如果开发的话,还要安装以下插件:1.maven插件2.svn插件3.gi

JSF+Spring开发时遇到的问题

问题描述 最近在用Spring+JSF进行web开发.但结合得不好,问题不断,这是我最新遇到的问题,那位大侠知道的指点一下啦~~我在faces-config.xml中这样设置,让spring的bean名称可以在JSF中使用:<application><variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver></application>

ajax返回中文乱码,servlet中的显示乱码,post提交的乱码问题,编码大总结

ajax|servlet|编码|问题|显示|中文|中文乱码 ajax返回中文乱码问题解决使用ajax获取服务器数据返回给客户端,出现中文乱码.在之前的一个ajax应用中指定codepage=936,将所有页面编码都指定为GB2312即可解决.这 次的应用中却无起作用了,经过多次的试验,客服端的编码应该绝对没有问题的.可以判断问题一定出在服务器端.稍微分析一下可知虽然服务器端指定了文件的编 码格式,但对于服务器输出流就成为了怀疑的对象.由于使用MS SQL2000,采用unicode编码,所以返回