最流行的方法就是  实现ApplicationContextAware接口

 

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 服务器启动,Spring容器初始化时,当加载了当前类为Bean组件后,
     * 将会调用下面方法注入ApplicationContext实例
     */
    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {  
        applicationContext = arg0;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

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

    public static <T> T getBean(String beanName, Class<T> tClass) {
        return applicationContext.getBean(beanName, tClass);
    }
}

使用的时候 就可以在任意地方调用了,当然也可以在 static 静态方法中进行使用,如下

    public static Integer getParentByOrgId(Integer orgId){
        UserRoleRelateRepository repository = SpringContextUtil.getBean(UserRoleRelateRepository.class);
        Integer parentId = repository.getParentIdbyId(orgId);
        return parentId;
    }

 

posted on 2021-09-02 15:28  菜霸  阅读(558)  评论(0编辑  收藏  举报