通过注解注入在spring里的bean的名称获取bean

==========》千里之行,始于足下
 
1.获取bean的code
package com.jinhuhang.listener;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
 *
 * Class Description:通过注入在spring中bean的名称获取bean
 *
 * Author:gaoqi  
 *
 * Date:2015-8-10 上午11:06:33  
 *
 */
public class SpringContextUtil implements ApplicationContextAware {
 
 private static ApplicationContext   applicationContext;
 
    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     */
    public void setApplicationContext(ApplicationContext applicationContext){
        SpringContextUtil.applicationContext = applicationContext;
    }
 
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }
 
    /**
     * 获取对象
     */
    public static Object getBean(String name) throws BeansException{
        return applicationContext.getBean(name);
    }
 
}
 
2.需要将此类注入到spring中,进行管理
 <bean class="com.jinhuhang.listener.SpringContextUtil"/>
 
 
3.使用方式
 private  IPhoneApproveService iPhoneApproveService = ( IPhoneApproveService)SpringContextUtil.getBean(" phoneApproveService");

猜你喜欢

转载自bigseven.iteye.com/blog/2234870