在SpringBoot主启动类中获取实例化的Bean
在SpringBoot主启动类中,如果要调用某个Bean的方法,就需要获取Spring容器中的Bean实例。此时可以通过Spring上下文来获取,方法如下:
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(this.applicationContext == null) { this.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); DemoDao demo = ApplicationContextUtil.getBean(DemoDao.class);
}
}
积极竞争
不惧失败
学习提升
不惧失败
学习提升