Java_web开发_SSH spring中取得Bean实例的方法 .(很强大,不能不转)

来源:互联网 发布:晋中教务网络管理系统 编辑:程序博客网 时间:2024/06/03 21:07

获得spring里注册Bean的四种方法,特别是第三种方法,简单:
一:方法一(多在struts框架中)继承BaseDispatchAction

 

[java] view plaincopyprint?
  1. import com.mas.wawacommunity.wap.service.UserManager;  
  2.    
  3. public class BaseDispatchAction extends DispatchAction {  
  4.     /** 
  5.     * web应用上下文环境变量 
  6.     */  
  7.     protected WebApplicationContext ctx;  
  8.    
  9.     protected UserManager userMgr;  
  10.    
  11.     /** 
  12.     * 获得注册Bean      
  13.     * @param beanName String 注册Bean的名称 
  14.     * @return 
  15.     */  
  16.     protected final Object getBean(String beanName) {  
  17.         return ctx.getBean(beanName);  
  18.     }  
  19.    
  20.     protected ActionForward unspecified(ActionMapping mapping, ActionForm form,  
  21.               javax.servlet.http.HttpServletRequest request,  
  22.               javax.servlet.http.HttpServletResponse response) {       
  23.         return mapping.findForward("index");  
  24.     }  
  25.    
  26.     public void setServlet(ActionServlet servlet) {  
  27.         this.servlet = servlet;  
  28.         this.ctx = WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());  
  29.         this.userMgr = (UserManager) getBean("userManager");  
  30.     }           
  31. }  
  


二:方法二实现BeanFactoryAware
一定要在spring.xml中加上:
<bean id="serviceLocator" class="项目中ServiceLocator的类路径比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />
当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用beanFactory


[java] view plaincopyprint?
  1. public class ServiceLocator implements BeanFactoryAware {  
  2.     private static BeanFactory beanFactory = null;  
  3.    
  4.     private static ServiceLocator servlocator = null;  
  5.    
  6.     public void setBeanFactory(BeanFactory factory) throws BeansException {  
  7.         this.beanFactory = factory;  
  8.     }  
  9.    
  10.     public BeanFactory getBeanFactory() {  
  11.         return beanFactory;  
  12.     }  
  13.    
  14.      
  15.     public static ServiceLocator getInstance() {  
  16.         if (servlocator == null)  
  17.               servlocator = (ServiceLocator) beanFactory.getBean("serviceLocator");  
  18.         return servlocator;  
  19.     }  
  20.    
  21.     /** 
  22.     * 根据提供的bean名称得到相应的服务类      
  23.     * @param servName bean名称      
  24.     */  
  25.     public static Object getService(String servName) {  
  26.         return beanFactory.getBean(servName);  
  27.     }  
  28.    
  29.     /** 
  30.     * 根据提供的bean名称得到对应于指定类型的服务类 
  31.     * @param servName bean名称 
  32.     * @param clazz 返回的bean类型,若类型不匹配,将抛出异常 
  33.     */  
  34.     public static Object getService(String servName, Class clazz) {  
  35.         return beanFactory.getBean(servName, clazz);  
  36.     }  
  37. }  
  


action调用:

 

[java] view plaincopyprint?
  1. public class UserAction extends BaseAction implements Action,ModelDriven{  
  2.       
  3.     private Users user = new Users();  
  4.     protected ServiceLocator service = ServiceLocator.getInstance();  
  5.     UserService userService = (UserService)service.getService("userService");  
  6.    
  7.     public String execute() throws Exception {           
  8.         return SUCCESS;  
  9.     }  
  10.    
  11.   public Object getModel() {  
  12.         return user;  
  13.     }       
  14.       
  15.     public String getAllUser(){  
  16.         HttpServletRequest request = ServletActionContext.getRequest();           
  17.         List ls=userService.LoadAllObject( Users.class );  
  18.         request.setAttribute("user",ls);       
  19.         this.setUrl("/yonghu.jsp");  
  20.         return SUCCESS;  
  21.     }  
  22. }  
  


三:方法三实现ApplicationContextAware
一定要在spring.xml中加上:
<bean id="SpringContextUtil " class="项目中applicationContext的类路径比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />
当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext
 

[java] view plaincopyprint?
  1. public class SpringContextUtil implements ApplicationContextAware {  
  2.   private static ApplicationContext applicationContext;     //Spring应用上下文环境  
  3.    
  4.   /** 
  5.   * 实现ApplicationContextAware接口的回调方法,设置上下文环境    
  6.   * @param applicationContext 
  7.   * @throws BeansException 
  8.   */  
  9.   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
  10.     SpringContextUtil.applicationContext = applicationContext;  
  11.   }  
  12.    
  13.   /** 
  14.   * @return ApplicationContext 
  15.   */  
  16.   public static ApplicationContext getApplicationContext() {  
  17.     return applicationContext;  
  18.   }  
  19.    
  20.   /** 
  21.   * 获取对象    
  22.   * @param name 
  23.   * @return Object 一个以所给名字注册的bean的实例 
  24.   * @throws BeansException 
  25.   */  
  26.   public static Object getBean(String name) throws BeansException {  
  27.     return applicationContext.getBean(name);  
  28.   }  
  29.    
  30.   /** 
  31.   * 获取类型为requiredType的对象 
  32.   * 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException) 
  33.   * @param name       bean注册名 
  34.   * @param requiredType 返回对象类型 
  35.   * @return Object 返回requiredType类型对象 
  36.   * @throws BeansException 
  37.   */  
  38.   public static Object getBean(String name, Class requiredType) throws BeansException {  
  39.     return applicationContext.getBean(name, requiredType);  
  40.   }  
  41.    
  42.   /** 
  43.   * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true  
  44.   * @param name 
  45.   * @return boolean 
  46.   */  
  47.   public static boolean containsBean(String name) {  
  48.     return applicationContext.containsBean(name);  
  49.   }  
  50.    
  51.   /** 
  52.   * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 
  53.   * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)    
  54.   * @param name 
  55.   * @return boolean 
  56.   * @throws NoSuchBeanDefinitionException 
  57.   */  
  58.   public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {  
  59.     return applicationContext.isSingleton(name);  
  60.   }  
  61.    
  62.   /** 
  63.   * @param name 
  64.   * @return Class 注册对象的类型 
  65.   * @throws NoSuchBeanDefinitionException 
  66.   */  
  67.   public static Class getType(String name) throws NoSuchBeanDefinitionException {  
  68.     return applicationContext.getType(name);  
  69.   }  
  70.    
  71.   /** 
  72.   * 如果给定的bean名字在bean定义中有别名,则返回这些别名    
  73.   * @param name 
  74.   * @return 
  75.   * @throws NoSuchBeanDefinitionException 
  76.   */  
  77.   public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {  
  78.     return applicationContext.getAliases(name);  
  79.   }  
  80. }  
  

 

action调用: 

[java] view plaincopyprint?
  1. package com.anymusic.oa.webwork;  
  2.    
  3. import java.util.List;  
  4. import java.util.Map;  
  5.    
  6. import javax.servlet.http.HttpServletRequest;  
  7.    
  8. import com.anymusic.oa.commons.service.ServiceLocator;  
  9. import com.anymusic.oa.hibernate.pojo.Role;  
  10. import com.anymusic.oa.hibernate.pojo.Users;  
  11. import com.anymusic.oa.spring.IUserService;  
  12. import com.opensymphony.webwork.ServletActionContext;  
  13. import com.opensymphony.xwork.Action;  
  14. import com.opensymphony.xwork.ActionContext;  
  15. import com.opensymphony.xwork.ModelDriven;  
  16.    
  17. public class UserAction extends BaseAction implements Action,ModelDriven{  
  18.       
  19.     private Users user = new Users();   
  20.  //不用再加载springContext.xml文件,因为在web.xml中配置了,在程序中启动是就有了.      
  21.     UserService userService = (UserService) SpringContextUtil.getBean("userService");  
  22.       
  23.     public String execute() throws Exception {           
  24.         return SUCCESS;  
  25.     }  
  26.    
  27.   public Object getModel() {  
  28.         return user;  
  29.     }       
  30.       
  31.     public String getAllUser(){  
  32.         HttpServletRequest request = ServletActionContext.getRequest();           
  33.         List ls=userService.LoadAllObject( Users.class );  
  34.         request.setAttribute("user",ls);       
  35.         this.setUrl("/yonghu.jsp");  
  36.         return SUCCESS;  
  37.     }  
  38. }  
  

 

四.通过servlet 或listener设置spring的ApplicationContext,以便后来引用.
注意分别extends  ContextLoaderListener和ContextLoaderServlet .然后就可用SpringContext来getBean.
覆盖原来在web.xml中配置的listener或servlet.

[java] view plaincopyprint?
  1. public class SpringContext  {  
  2.   private static ApplicationContext applicationContext;     //Spring应用上下文环境  
  3.    
  4.   
  5.   */  
  6.   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
  7.     SpringContextUtil.applicationContext = applicationContext;  
  8.   }  
  9.    
  10.   /** 
  11.   * @return ApplicationContext 
  12.   */  
  13.   public static ApplicationContext getApplicationContext() {  
  14.     return applicationContext;  
  15.   }  
  16.    
  17.   
  18.   */  
  19.   public static Object getBean(String name) throws BeansException {  
  20.     return applicationContext.getBean(name);  
  21.   }  
  22.   
  23. }  
  24.   
  25. public class SpringContextLoaderListener extends ContextLoaderListener{  //  
  26.  public void contextInitialized(ServletContextEvent event) {    
  27.   super.contextInitialized(event);  
  28.   SpringContext.setApplicationContext(  
  29.     WebApplicationContextUtils.getWebApplicationContext(event.getServletContext())  
  30.     );  
  31.  }  
  32. }  
  33.   
  34. public class SpringContextLoaderServlet extends ContextLoaderServlet {  
  35.  private ContextLoader contextLoader;  
  36.     public void init() throws ServletException {  
  37.         this.contextLoader = createContextLoader();  
  38.         SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext()));  
  39.     }  
  40. }  
  

 

自己使用:

 

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");

原创粉丝点击