SpringBoot ApplicationContext 获取 Bean

方式一是实现:implements ApplicationContextAware

方式二是直接设置ApplicationContext类,但是需要在Springboot 启动时setApplicationContext

 方式一的写法

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static   T getBean(Class t){
        try {
            return (T)applicationContext.getBean(t);
        }catch (BeansException e){
            return null;
        }
    }

    public static   T  getBean(String name){
        try {
            return (T)applicationContext.getBean(name);
        }catch (BeansException e){
            return null;
        }
    }
}
SpringContextUtil.getBean("")

方式二的写法

@Component
public class SpringContextUtil {

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static   T getBean(Class t){
        try {
            return (T)applicationContext.getBean(t);
        }catch (BeansException e){
            return null;
        }
    }

    public static   T  getBean(String name){
        try {
            return (T)applicationContext.getBean(name);
        }catch (BeansException e){
            return null;
        }
    }
}

 启动注入然后设置上下文信息


@SpringBootApplication
@MapperScan(basePackages ="com.doug.proxydatapoi.mapper")
public class DougExcelApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DougExcelApplication.class, args);
        SpringContextUtil.setApplicationContext(applicationContext);
    }

}

调用方式和方式一一致。

注意点:方式一和方式二的调用方式相同,不同的是上下文的设置时间。方式一在启动时注入可能会获取不到,方式二回避免这类问题。

你可能感兴趣的:(SpringBoot,spring,spring,boot)