Java_web開發_SSH spring中取得Bean實例的方法 .

獲得spring裏註冊Bean的四種方法,特別是第三種方法,簡單:
一:方法一(多在struts框架中)繼承BaseDispatchAction

 

[java] view plaincopyprint?

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");  
    }           
}  
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="項目中ServiceLocator的類路徑比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />
當對serviceLocator實例時就自動設置BeanFactory,以便後來可直接用beanFactory


[java] view 
plaincopyprint?
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);  
    }  
}


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調用:

 

[java] view 
plaincopyprint?
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;  
    }  
}


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="項目中applicationContext的類路徑比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />
當對SpringContextUtil 實例時就自動設置applicationContext,以便後來可直接用applicationContext
 

[java] view 
plaincopyprint?
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);  
  }  
}


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] view plaincopyprint?

  1. 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;  
        }  
    }

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.


[java] view 
plaincopyprint?
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()));  
    }  
}


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


 

自己使用:

 

1.如果applicationContext文件是在src的根目錄下:

 

ApplicationContext apt= new 
FileSystemXmlApplicationContext("src/applicationContext.xml");
apt.getBean("ID");

可以取得

 

2.如果文件是在WebRoot/WEB-INF下可以用

ApplicationContext applicationContext= new 
FileSystemXmlApplicationContext("../applicationContext.xml");

取得

 

3.如果是在servlet中取可用

  ServletContext application = 
this.getServletContext();
  
  //獲取spring上下文信息 
爲servlet使用
  WebApplicationContext wac = 
WebApplicationContextUtils.getWebApplicationContext(application);
  IDicService 
dicService = (IDicService)wac.getBean("dicService");

轉載  songylwq的專欄


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章