天天看點

Web開發中擷取Spring的ApplicationContext的幾種方式

在 WEB 開發中,擷取到由 Spring 進行管理的某些 Bean,通常采用下面方式來擷取

1、通過set注入方式

private ProjectStageHandler projectStageHandler;

public void setProjectStageHandler(ProjectStageHandler projectStageHandler) {
  this.projectStageHandler = projectStageHandler;
 }

           

2、通過注解方式

@Resource

private ProjectStageHandler projectStageHandler;

           

今天遇到 需要顯示的獲得 ApplicationContext 來得到由 Spring 進行管理的某些 Bean,在這裡和大家分享一下,WEB 開發中,怎麼擷取 ApplicationContext ( 如有不正确之處還請指點)

查找工程有沒有這種實作,功夫沒有白費還真找到了大緻實作方式如下:

3、首先web.xml配置

<listener>
    	<listener-class>org.common.xxxServletContextListener</listener-class>
    </listener>      

接着xxxServletContextListener.java

public class xxxServletContextListener implements ServletContextListener {    
    //ServletContext建立時調用該方法 
	public void contextInitialized(ServletContextEvent arg0){
		ServletContext context= arg0.getServletContext();   
		System.out.println("監聽器啟動。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
		ApplicationCtx.init(context);
	}  
    //ServletContext銷毀時調用該方法    
    public void contextDestroyed(ServletContextEvent sce){    
         System.out.println("ServletContext銷毀");    
     }
	  
}   
           

ApplicationCtx .java

public class ApplicationCtx {

	public static ApplicationContext ctx;
	
	public static ApplicationContext getCtx(){
		return ctx;
	}
	public static void init(ServletContext sc){
		if(ctx==null){
			ctx =  WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		}
	}
}
           

通過 ApplicationCtx.getCtx().getBean("xxx"); 就可以獲到想要的bean啦

想想這種方式有點太羅嗦和麻煩,還有沒有更簡單的方式哪?有當然有。

4、首先要在spring.xml中加上

<bean id="applicationContext" class="org.wy.util.AppliactionContextHelper"/>      

當對AppliactionContextHelper執行個體時就自動設定applicationContext,以便後來可直接用applicationContext

public class AppliactionContextHelper implements ApplicationContextAware {
  private static ApplicationContext applicationContext;     //Spring應用上下文環境
 
  /**
  * 實作ApplicationContextAware接口的回調方法,設定上下文環境  
  * @param applicationContext
  * @throws BeansException
  */
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    AppliactionContextHelper.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);
  }
}
           

通過AppliactionContextHelper.getBean("xxx");就可以獲到想要的bean啦

5、

利用ClassPathXmlApplicationContext

可以從classpath中讀取XML檔案

(1) ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

UserDao userDao = (UserDao)context.getBean("userDao");

(2) ClassPathXmlApplicationContext resource = new ClassPathXmlApplicationContext(new String[]{"applicationContext-ibatis-oracle.xml","applicationContext.xml","applicationContext-data-oracle.xml"});

BeanFactory factory = resource;

factory.getBean("xxx");

這種方式隻适合非web中的應用程式中。

--------------------------------------------------------------------------------------------------------------------------------

轉載:

獲得spring裡注冊Bean的四種方法,特别是第三種方法,簡單:

一:方法一(多在struts架構中)繼承BaseDispatchAction

Java代碼

Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
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中加上:

Xml代碼

Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
<bean id="serviceLocator" class="com.am.oa.commons.service.ServiceLocator" singleton="true" />
      

當對serviceLocator執行個體時就自動設定BeanFactory,以便後來可直接用 beanFactory

Java代碼

Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
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中加上:

Xml代碼

Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
<bean id="SpringContextUtil " class="com.am.oa.commons.service.SpringContextUtil " singleton="true" />
      

當對SpringContextUtil 執行個體時就自動設定applicationContext,以便後來可直接用applicationContext

Java代碼

Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的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調用:

Java代碼

Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
Web開發中擷取Spring的ApplicationContext的幾種方式
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()));   
    }   
}