1、簡介app
咱們開發時,常常遇到有些實例須要動態建立,好比有構造函數的組件等。這時候,Spring時咱們有ClassPathXmlApplicationContext,可是在Spring Boot時,咱們怎麼拿到ApplicationContext對像來調用它的GetBean方法呢?dom
2、方案函數
一、方案一:直接注入spa
@Component public class MyClass { @Autowired private ApplicationContext applicationContext; }
二、方案二:利用SpringBootApplication的run方法返回的Context,存到項目靜態變量中使用。code
@SpringBootApplication @EntityScan("com.dearcloud.domain.po") @EnableJpaRepositories(basePackages = "com.dearcloud.repository") @EnableDubbo public class ApplicationServer { public static void main(String[] args) { //啓動WEB項目 SpringApplication application = new SpringApplication(ApplicationServer.class); ConfigurableApplicationContext context = application.run(args); UserPoJpaRepository userPoJpaRepository = context.getBean(UserPoJpaRepository.class); } }