获得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()));
}
}

Spring-程序中获取注册bean的方式的更多相关文章

  1. spring通过注解注册bean的方式+spring生命周期

    spring容器通过注解注册bean的方式 @ComponentScan + 组件标注注解 (@Component/@Service...) @ComponentScan(value = " ...

  2. 从Spring容器中获取Bean。ApplicationContextAware

    引言:我们从几个方面有逻辑的讲述如何从Spring容器中获取Bean.(新手勿喷) 1.我们的目的是什么? 2.方法是什么(可变的细节)? 3.方法的原理是什么(不变的本质)? 1.我们的目的是什么? ...

  3. 获取并打印Spring容器中所有的Bean名称

    思路: 1.实现Spring的ApplicationContextAware接口,重写setApplicationContext方法,将得到的ApplicationContext对象保存到一个静态变量 ...

  4. java 从spring容器中获取注入的bean对象

      java 从spring容器中获取注入的bean对象 CreateTime--2018年6月1日10点22分 Author:Marydon 1.使用场景 控制层调用业务层时,控制层需要拿到业务层在 ...

  5. 转:深入浅出spring IOC中四种依赖注入方式

    转:https://blog.csdn.net/u010800201/article/details/72674420 深入浅出spring IOC中四种依赖注入方式 PS:前三种是我转载的,第四种是 ...

  6. Spring的几种注入bean的方式

    在Spring容器中为一个bean配置依赖注入有三种方式: · 使用属性的setter方法注入  这是最常用的方式: · 使用构造器注入: · 使用Filed注入(用于注解方式).   使用属性的se ...

  7. 深入浅出spring IOC中三种依赖注入方式

    深入浅出spring IOC中三种依赖注入方式 spring的核心思想是IOC和AOP,IOC-控制反转,是一个重要的面向对象编程的法则来消减计算机程序的耦合问题,控制反转一般分为两种类型,依赖注入和 ...

  8. linux c程序中获取shell脚本输出的实现方法

    linux c程序中获取shell脚本输出的实现方法 1. 前言Unix界有一句名言:“一行shell脚本胜过万行C程序”,虽然这句话有些夸张,但不可否认的是,借助脚本确实能够极大的简化一些编程工作. ...

  9. java程序中获取kerberos登陆hadoop

    本文由作者周梁伟授权网易云社区发布. 一般我们在使用kbs登陆hadoop服务时都直接在shell中调用kinit命令来获取凭证,这种方式简单直接,只要获取一次凭证之后都可以在该会话过程中重复访问.但 ...

随机推荐

  1. nginx作为负载均衡服务器——测试

    i. 需求 nginx作为负载均衡服务器,用户请求先到达nginx,再由nginx根据负载配置将请求转发至 tomcat服务器. nginx负载均衡服务器:192.168.101.3 tomcat1服 ...

  2. java 24 - 4 GUI之创建数据转移窗口

    需求: 把文本框中的数据,通过点击按钮,转移到文本域中.  同时清空文本框中的数据 代码:(步骤都注释了) public class FrameDemo4 { public static void m ...

  3. checkbox与jq<转>2

    jQuery中attr()解决checked属性问题 作者:u012885111 这两天在做一个表单提交,其中就包含有checkbox的全选和反选,这是最先开始做出来的版本,代码如下: <inp ...

  4. 苹果IOS开发者账号总结--发布应用APP时team name是否可以随意写?

    个人账号(Individual): 费用99美金一年, 该账号在App Store销售者只能显示个人的ID,比如zhitian zhang,单人使用.个人账号只能有一个开发者.100个苹果的iOS设备 ...

  5. 【MVC】自定义Scaffold Template

    MVC提供了基本的CRUD Scaffold Template模板,创建视图的时候,只要勾选创建一个强类型视图 , 并选择模型类,就可以选择支架模板了,这些模板包括List,Detail,Create ...

  6. 重构Web Api程序(Api Controller和Entity) 续篇(1)

    经过一系列重构,你眼明的话,还是可以看到还有重构的地方,如: string newFileName = "~/Temp/" + Guid.NewGuid().ToString() ...

  7. IntelliJ IDEA 13试用手记(附详细截图)

    从去年开始转java以来,一直在寻找一款趁手的兵器,eclipse虽然是很多java程序员的首选,但是我发现一旦安装了一些插件,workspace中的项目达到数10个以后,经常崩溃,实在影响编程的心情 ...

  8. 让python在hadoop上跑起来

    duang~好久没有更新博客啦,原因很简单,实习啦-好吧,我过来这边上班表示觉得自己简直弱爆了.第一周,配置环境:第二周,将数据可视化,包括学习了excel2013的一些高大上的技能,例如数据透视表和 ...

  9. Clock Skew , Clock Uncertainty和 Period

    本文将介绍FPGA中和时钟有关的相关概念,阅读本文前需要对时序收敛的基本概念和建立.保持关系有一定了解,这些内容可以在时序收敛:基本概念,建立时间和保持时间(setup time 和 hold tim ...

  10. 深入理解OOP(二):多态和继承(继承)

    本文是深入浅出OOP第二篇,主要说说继承的话题. 深入理解OOP(一):多态和继承(初期绑定和编译时多态) 深入理解OOP(二):多态和继承(继承) 深入理解OOP(三):多态和继承(动态绑定和运行时 ...