获得spring的容器

ApplicationContextAware

  • 获得Spring容器的工具类

获得Spring容器的工具类

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

import java.util.Map;

@Component
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext ctx = null;

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

    public static  T getBean(Class clazz) {
        return (T) ctx.getBean(clazz);
    }

    public static Object getBean(String name) {
        return ctx.getBean(name);
    }

    public static  Map getBeansOfType(Class type) {
        return ctx.getBeansOfType(type);
    }
}

可以当一个工具类 SpringContextUtils.getBean(“xxxx”);来拿到spring容器中的bean

你可能感兴趣的:(获得spring的容器)