`

web中spring获取bean

 
阅读更多
最近在用mybatis+spring,但是因为数据库是集群,所以要对sqlsession或者sessionFactoryBean分开管理,就要通过bean分别获取session,并且为了serviceAction和model的解耦,所以就想在model层引入session,平时session和事务之所以放在control层管理,就是因为一般这一层是直接访问bean,所以里面在这里注入session和事务可以直接获得spring applicationContext 中的bean,要我现在为了解耦(实际上在这里通过@Autowried(request=true/false)只是编译解耦运行实际是不解偶的,因为不申明Autowried下的bean编译可以通过但是运行会报错,beanCreateException)就想在model层来获取bean,下面的文章写的不错
http://dearseven.blog.163.com/blog/static/10053792220122410381684/


获得spring里注册Bean的四种方法,特别是第三种方法,简单:
一:方法一(多在struts框架中)继承BaseDispatchAction


import com.mas.wawacommunity.wap.service.UserManager;

public class BaseDispatchAction extends DispatchAction {
    /**
    * web应用上下文环境变量
    */
    protected WebApplicationContext ctx;

    protected UserManager userMgr;

    /**
    * 获得注册Bean    
    * @param beanName String 注册Bean的名称
    * @return
    */
    protected final Object getBean(String beanName) {
        return ctx.getBean(beanName);
    }

    protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
              javax.servlet.http.HttpServletRequest request,
              javax.servlet.http.HttpServletResponse response) {    
        return mapping.findForward("index");
    }

    public void setServlet(ActionServlet servlet) {
        this.servlet = servlet;
        this.ctx = WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());
        this.userMgr = (UserManager) getBean("userManager");
    }        
}





二:方法二实现BeanFactoryAware
一定要在spring.xml中加上:
<bean id="serviceLocator" class="com.am.oa.commons.service.ServiceLocator" singleton="true" />
当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用beanFactory


public class ServiceLocator implements BeanFactoryAware {
    private static BeanFactory beanFactory = null;

    private static ServiceLocator servlocator = null;

    public void setBeanFactory(BeanFactory factory) throws BeansException {
        this.beanFactory = factory;
    }

    public BeanFactory getBeanFactory() {
        return beanFactory;
    }

  
    public static ServiceLocator getInstance() {
        if (servlocator == null)
              servlocator = (ServiceLocator) beanFactory.getBean("serviceLocator");
        return servlocator;
    }

    /**
    * 根据提供的bean名称得到相应的服务类    
    * @param servName bean名称    
    */
    public static Object getService(String servName) {
        return beanFactory.getBean(servName);
    }

    /**
    * 根据提供的bean名称得到对应于指定类型的服务类
    * @param servName bean名称
    * @param clazz 返回的bean类型,若类型不匹配,将抛出异常
    */
    public static Object getService(String servName, Class clazz) {
        return beanFactory.getBean(servName, clazz);
    }
}



action调用:


public class UserAction extends BaseAction implements Action,ModelDriven{
   
    private Users user = new Users();
    protected ServiceLocator service = ServiceLocator.getInstance();
    UserService userService = (UserService)service.getService("userService");

    public String execute() throws Exception {        
        return SUCCESS;
    }

  public Object getModel() {
        return user;
    }    
   
    public String getAllUser(){
        HttpServletRequest request = ServletActionContext.getRequest();        
        List ls=userService.LoadAllObject( Users.class );
        request.setAttribute("user",ls);    
        this.setUrl("/yonghu.jsp");
        return SUCCESS;
    }
}



三:方法三实现ApplicationContextAware
一定要在spring.xml中加上:
<bean id="SpringContextUtil " class="com.am.oa.commons.service.SpringContextUtil " singleton="true" />
当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext



public class SpringContextUtil implements ApplicationContextAware {
  private static ApplicationContext applicationContext;     //Spring应用上下文环境

  /**
  * 实现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);
  }

  /**
  * 获取类型为requiredType的对象
  * 如果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);
  }

  /**
  * 如果给定的bean名字在bean定义中有别名,则返回这些别名  
  * @param name
  * @return
  * @throws NoSuchBeanDefinitionException
  */
  public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.getAliases(name);
  }
}




action调用:
package com.anymusic.oa.webwork;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.anymusic.oa.commons.service.ServiceLocator;
import com.anymusic.oa.hibernate.pojo.Role;
import com.anymusic.oa.hibernate.pojo.Users;
import com.anymusic.oa.spring.IUserService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ModelDriven;

public class UserAction extends BaseAction implements Action,ModelDriven{
   
    private Users user = new Users();
//不用再加载springContext.xml文件,因为在web.xml中配置了,在程序中启动是就有了.   
    UserService userService = (UserService) SpringContextUtil.getBean("userService");
   
    public String execute() throws Exception {        
        return SUCCESS;
    }

  public Object getModel() {
        return user;
    }    
   
    public String getAllUser(){
        HttpServletRequest request = ServletActionContext.getRequest();        
        List ls=userService.LoadAllObject( Users.class );
        request.setAttribute("user",ls);    
        this.setUrl("/yonghu.jsp");
        return SUCCESS;
    }
}




四.通过servlet 或listener设置spring的ApplicationContext,以便后来引用.
注意分别extends  ContextLoaderListener和ContextLoaderServlet .然后就可用SpringContext来getBean.
覆盖原来在web.xml中配置的listener或servlet.

public class SpringContext  {
  private static ApplicationContext applicationContext;     //Spring应用上下文环境


  */
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextUtil.applicationContext = applicationContext;
  }

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


  */
  public static Object getBean(String name) throws BeansException {
    return applicationContext.getBean(name);
  }

}

public class SpringContextLoaderListener extends ContextLoaderListener{  //
public void contextInitialized(ServletContextEvent event) { 
  super.contextInitialized(event);
  SpringContext.setApplicationContext(
    WebApplicationContextUtils.getWebApplicationContext(event.getServletContext())
    );
}
}

public class SpringContextLoaderServlet extends ContextLoaderServlet {
private ContextLoader contextLoader;
    public void init() throws ServletException {
        this.contextLoader = createContextLoader();
        SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext()));
    }
}
分享到:
评论

相关推荐

    在web容器(WebApplicationContext)中获取spring中的bean

    Spring把Bean放在这个容器中,普通的类在需要的时候,直接用getBean()方法取出

    Web项目中获取SpringBean与在非Spring组件中获取SpringBean.pdf

    ...

    Web项目中获取SpringBean与在非Spring组件中获取SpringBean.docx

    ...

    在Servlet直接获取Spring框架中的Bean.docx

    介绍了在Servlet直接获取Spring框架中的Bean.docx

    JSP 中Spring Bean 的作用域详解

    JSP 中Spring Bean 的作用域详解 Bean元素有一个scope属性,用于定义Bean的作用域,该属性有如下五个值: 1&gt;singleton: 单例模式,在整个spring IOC容器中,单例模式作用域...这种作用域只有在Web应用中使用Spring容

    用于获取Spring Bean依赖关系图的工具(高分毕设).zip

    Java SSM项目是一种使用Java语言和SSM框架(Spring + Spring MVC + MyBatis)开发的Web应用程序。SSM是一种常用的Java开发框架组合,它结合了Spring框架、Spring MVC框架和MyBatis框架的优点,能够快速构建可靠、...

    Spring中的Bean的管理_Bean的装配方式_基于注解的装配_项目

    目的:Spring容器已经成功获取了UserController实例,并通过调用实例中的方法执行了各层中的输出语句。 运行结果为: User [id=1, name=张三, password=123] userDao say hello world! UserService say hello world ...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.1.1. @Configurable object的单元测试 6.8.1.2. 多application context情况下的处理 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来...

    struts2+spring+hibernate整合示例

    c 测试类中 主动解析applicationContext.xml ,获取bean 执行dao层方法进行测试 2 将struts2 整合进去, 这次在struts.xml中我们使用通配符的方式配置action。 a 加入支持 : 添加struts2.3.15 必需包 以及 struts ...

    Spring in Action(第二版 中文高清版).part2

    第9章 在Spring中建立契约优先Web服务 9.1 介绍Spring-WS 9.2 定义契约(首先!) 9.3 使用服务端点处理消息 9.3.1 建立基于JDOM消息的端点 9.3.2 序列化消息载荷 9.4 合并在一起 9.4.1 Spring-WS:全景视图 ...

    Spring in Action(第二版 中文高清版).part1

    第9章 在Spring中建立契约优先Web服务 9.1 介绍Spring-WS 9.2 定义契约(首先!) 9.3 使用服务端点处理消息 9.3.1 建立基于JDOM消息的端点 9.3.2 序列化消息载荷 9.4 合并在一起 9.4.1 Spring-WS:全景视图 ...

    Spring攻略(第二版 中文高清版).part1

    3.7 在你的Bean中引入行为 132 3.7.1 问题 132 3.7.2 解决方案 132 3.7.3 工作原理 132 3.8 为你的Bean引入状态 135 3.8.1 问题 135 3.8.2 解决方案 135 3.8.3 工作原理 135 3.9 用基于XML的配置...

    Spring攻略(第二版 中文高清版).part2

    3.7 在你的Bean中引入行为 132 3.7.1 问题 132 3.7.2 解决方案 132 3.7.3 工作原理 132 3.8 为你的Bean引入状态 135 3.8.1 问题 135 3.8.2 解决方案 135 3.8.3 工作原理 135 3.9 用基于XML的配置...

    spring杂谈 作者zhang KaiTao

    1.11 在spring中获取代理对象代理的目标对象工具类 1.12 如何为spring代理类设置属性值 1.13 我对SpringDAO层支持的总结 1.14 我对SpringDAO层支持的总结 1.15 我对SpringDAO层支持的总结 1.16 我对Spring 容器管理...

    Spring_Framework_ API_5.0.5 (CHM格式)

    Spring Web Reactive 在 spring-webmvc 模块中现有的(而且很流行)Spring Web MVC旁边的新的 spring-web-reactive 模块中。 请注意,在 Spring5 中,传统的 SpringMVC 支持 Servlet3.1 上运行,或者支持 JavaEE7 的...

    Spring in Action(第2版)中文版

    第9章在spring中建立契约优先web服务 9.1介绍spring-ws 9.2定义契约(首先!) 9.3使用服务端点处理消息 9.3.1建立基于jdom消息的端点 9.3.2序列化消息载荷 9.4合并在一起 9.4.1spring-ws:全景视图 9.4.2将...

    Spring 2.0 开发参考手册

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. ...

    Spring+3.x企业应用开发实战光盘源码(全)

     第12章:讲解了如何在Spring中集成Hibernate、myBatis等数据访问框架,同时,读者还将学习到ORM框架的混用和DAO层设计的知识。  第13章:本章重点对在Spring中如何使用Quartz进行任务调度进行了讲解,同时还涉及...

    spring框架技术+第2天+xmind思维导图

    spring框架技术+第2天+xmind思维导图:生命周期,介绍simple project,打印出构造方法...bean作用域request session globalSession:web项目获取核心配置文件要配置两个地方:spring监听器、spring作用域范围的监听。

Global site tag (gtag.js) - Google Analytics