Spring:在普通Java类中获取由Spring所管理的Bean

  一般情况下,在使用SPRING注解的方式管理bean时,只能通过注解或者配置文件注入的方式获取相应的bean。

  但是在某些特殊情况下,我们需要在一个普通的JAVA类中获取由spring所管理的bean,下面是解决办法之一:

  

第一步:创建一个类并让其实现org.springframework.context.ApplicationContextAware接口,使Spring在启动时注入ApplicationContext对象:

package com.hsoft.mss.common.utils;
  
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
  
public class MyApplicationContextUtil implements ApplicationContextAware { 
      
  private static ApplicationContext context;
     
  public void setApplicationContext(ApplicationContext contex) throws BeansException { 
        MyApplicationContextUtil.context=contex; 
  }

  public static ApplicationContext getContext(){
    return context;   } }

 

第二步:在spring配置文件中注册上述bean,令服务器启动时加载并将contex对象注入其中:

<bean class="com.hsoft.mss.common.utils.MyApplicationContextUtil"></bean> 

 

第三步:通过上述方法获取重写的contex对象,并通过spring所管理的bean名称得到相应的对象,之后即可使用对象中的各种方法:

//获取LcfwDao 对象
LcfwDao lcfwDao = (LcfwDao) MyApplicationContextUtil.getContext().getBean("lcfwDaoImpl"); 
//调用其中的方法
int count = lcfwDao.getCountById("18");

 

posted @ 2014-05-26 22:15  .安之  阅读(4044)  评论(1编辑  收藏  举报