利用 ApplicationContextAware 获取spring bean

1.

<bean id="springContextUtil" class="com.xx.SpringContextUtil"/>

2.

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/****
 * SpringContext 上下文
 * 通过SpringContext获取Spring管理的业务Bean对象
 *
 */
public class SpringContextUtil implements ApplicationContextAware {
   
   private static ApplicationContext applicationContext;

   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      SpringContextUtil.applicationContext = applicationContext;
   }
   
   public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
      
    public static Object getBean(String name) throws BeansException {  
        return applicationContext.getBean(name);  
    }  

}

3.调用

private Iservice service;

public MyBatchProcess(){
    this.service= (Iservice)SpringContextUtil.getBean("service");
}

猜你喜欢

转载自blog.csdn.net/bighacker/article/details/81707299