⑤. 底层注解@Import导入组件
- ①. @Import({User.class, DBHelper.class})给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
- ②. 代码展示如下
@Import({User.class, DBHelper.class}) @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件 public class MyConfig { }
//1、返回我们IOC容器 ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); //... //5、获取组件 String[] beanNamesForType = run.getBeanNamesForType(User.class); for (String s : beanNamesForType) { //com.xiaozhi.bean.User //user01 System.out.println(s); } DBHelper bean1 = run.getBean(DBHelper.class); //ch.qos.logback.core.db.DBHelper@188cbcde System.out.println(bean1);
⑥. 底层注解@Conditional条件装配
- ①. 条件装配:满足Conditional指定的条件,则进行组件注入
②. 用@ConditionalOnMissingBean举例说明
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件 //有tom名字的Bean时,MyConfig类的Bean才能生效 @ConditionalOnBean(name="tom") public class MyConfig { //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例 @Bean //当容器中有tom组件的时候,才给注册user01 //@ConditionalOnBean(name="tom") public User user01(){ User zhangsan = new User("zhangsan", 18); //user组件依赖了Pet组件 zhangsan.setPet(tomcatPet()); return zhangsan; } //@Bean("tom") @Bean("tom2") public Pet tomcatPet(){ return new Pet("tomcat"); } }
@SpringBootApplication //等同于如下三个注解 //@SpringBootConfiguration //@EnableAutoConfiguration //@ComponentScan("com")//可以扫描com及com下的所有包 public class MainApplication { public static void main(String[] args) { //1.返回我们的IOC容器 ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); boolean tomFlag = run.containsBean("tom"); System.out.println("容器中是否有tom组件"+tomFlag);//false boolean user01Flag = run.containsBean("user01"); System.out.println("容器中是否有user01组件"+user01Flag);//true boolean tom2 = run.containsBean("tom2"); System.out.println("容器中tom2组件:"+tom2);//true } }