1. 程式人生 > 其它 >手動獲取 Bean 的幾種方式

手動獲取 Bean 的幾種方式

直接注入

@Component
public class BeanUtil {
    @Autowired
    private ApplicationContext applicationContext;

    public <T>T getBean(String BeanName){

        return (T)applicationContext.getBean("BeanName");
    }

    public <T>T getBean(Class cls){
        return (T)applicationContext.getBean(cls);
    }
}

通過 ApplicationContextAware 介面獲取

public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    
/** * 通過名稱獲取bean */ public static <T>T getBeanByName(String beanName){ return (T) applicationContext.getBean(beanName); } /** * 通過型別獲取bean */ public static <T>T getBeanByType(Class<T> clazz){ return (T) applicationContext.getBean(clazz); } }

通過 HttpServletRequest 獲取

ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
IBEmpService service = (IBEmpService) applicationContext.getBean("BeanName");