2.主程序类
1 @SpringBootApplication(scanBasePackages={"com.atguigu"}) 2 public class MainApplication { 3 public static void main(String[] args) { 4 //1.返回IOC容器 5 ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); 6 //2.获取容器内所有组件的名称 7 String[] names = run.getBeanDefinitionNames(); 8 for (String name : names) { 9 System.out.println(name); 10 } 11 12 13 //获取指定组件类型的所有组件名称 14 String[] beanNamesForType = run.getBeanNamesForType(User.class); 15 //com.atguigu.boot.bean.User --->通过@Import({User.class})在容器中自动创建的组件,默认组件名是全类名 16 //user01 --->配置类中通过@Bean给容器注册组件,组件名默认是方法名 17 //haha --->从spring配置文件beans.xml导入添加到容器中的haha组件 18 for (String bean : beanNamesForType) { 19 System.out.println(bean); 20 } 21 22 boolean tomcatPet = run.containsBean("tomcatPet"); 23 System.out.println("容器中是否有tomcatPet组件? " + tomcatPet); 24 25 boolean user01 = run.containsBean("user01"); 26 System.out.println("容器中是否有user01组件? " + user01); 27 28 //spring配置文件beans.xml只有导入到了容器中, 29 //这个配置文件中配置的bean才能添加到容器中 30 //导入方式:一般在配置类上加上@ImportResource("classpath:beans.xml"), 31 // 括号内指定xml的文件路径 32 boolean haha = run.containsBean("haha"); 33 boolean hehe = run.containsBean("hehe"); 34 System.out.println(haha); 35 System.out.println(hehe); 36 37 Car car = run.getBean(Car.class); 38 System.out.println(car); 39 40 } 41 }