手动获取 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");

 

posted @ 2022-03-30 11:56  Lucky_Coke  阅读(679)  评论(0)    收藏  举报