1. 程式人生 > >幾種獲取spring環境上下文方法

幾種獲取spring環境上下文方法

 

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