SessionListener与Spring

分类:Tech | 作者:Shoopman | 发表于2009/07/10 没有评论  

    在SessionListener里,需要使用被Spring管理起来的其他Bean,如某些DAO或者Manager、Service。在实现这个过程是这样的:

    1.把SessionListener也交给Spring来管理。

    由于使用了Spring Annotation,所以在SessionListener上加了@Service标记,并且把需要用到的其他Bean在SessionListener中定义为成员变量并加上@Autowried。但结果是失败的,SessionListener里的其他Bean没有被注入。

    2.直接通过Spring的Context来获得相应的DAO等的实例。

    Spring Annotation默认是ByType的方式来注入Bean,因此写了一个静态方法来获取相关的Bean,不知道有没有其他更好的办法,请告诉我吧:

/**
* 根据类型从Spring中取得Bean
*
* @param <T>    Bean的类型
* @param beanClass    Bean的Class对象
* @param servletContext   
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getSpringBean(Class<T> beanClass,
        ServletContext servletContext) {
    WebApplicationContext appContext = (WebApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    Map beans = appContext.getBeansOfType(beanClass);
    if (beans == null || beans.isEmpty()) {
        return null;
    }
    return (T) beans.values().toArray()[0];
}