spring 几种获得bean的方法

本文介绍了在Spring框架中获取Bean的四种实用方法:通过继承BaseDispatchAction、实现BeanFactoryAware接口、实现ApplicationContextAware接口以及通过servlet或listener设置ApplicationContext。每种方法都提供了详细的代码示例。
获得spring里注册Bean的四种方法,特别是第三种方法,简单: 
一:方法一(多在struts框架中)继承BaseDispatchAction 
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调用:

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

转自:http://jitaguizhao.iteye.com/blog/223832
参考:http://jsjxqjy.iteye.com/blog/550754

Spring基于XML注入Bean主要有以下几种方式: ### 属性注入(setter方法注入) 通过在XML中使用`<property>`标签,调用Bean的setter方法来注入属性值。可以进行值类型注入(如基本数据类型)和引用类型注入(将依赖对象注入)。示例如下: ```xml <bean name="teacher" class="org.springframework.demo.model.Teacher"> <property name="name" value="阿Q"></property> </bean> ``` 这里通过`value`属性为`Teacher`类的`name`属性注入了一个字符串值。对于引用类型注入,如下: ```xml <bean id="owner" class="com.practice.Owner"> <property name="name" value="Tom" /> <property name="age" value="17" /> </bean> <bean id="dog" class="com.practice.Dog"> <property name="owner" ref="owner" /> </bean> ``` 在这个例子中,`dog` Bean的`owner`属性通过`ref`引用了`owner` Bean,实现了引用类型的注入[^2][^3]。 ### 构造方法注入 通过`<constructor-arg>`标签,使用构造方法来注入属性值。示例如下: ```xml <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" ref="anotherExampleBean"/> </bean> ``` `index`属性指定了构造方法参数的索引,`value`用于注入值类型,`ref`用于注入引用类型。 ### p命名空间注入 p命名空间提供了一种更简洁的属性注入方式。首先需要在XML文件中引入p命名空间: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> ``` 然后使用`p:`前缀进行属性注入,示例如下: ```xml <bean id="myBean" class="com.example.MyBean" p:property1="value1" p:property2-ref="anotherBean"/> ``` `p:property1`用于注入值类型,`p:property2-ref`用于注入引用类型。 ### c命名空间注入 c命名空间用于简化构造方法注入。同样需要先引入c命名空间: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> ``` 示例如下: ```xml <bean id="exampleBean" class="examples.ExampleBean" c:_0="7500000" c:_1-ref="anotherExampleBean"/> ``` `c:_0`表示构造方法的第一个参数,`c:_1-ref`表示构造方法的第二个参数为引用类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值