第六章 SpringBoot注解 @ConditionalOnBean

满足条件的则进行组件的注入

第六章 SpringBoot注解 @ConditionalOnBean_第1张图片

@Configuration(proxyBeanMethods = true) //告诉SpringBoot这是一个配置类 == 配置文件
@ConditionalOnBean(name = "tom")
public class MyConfig {

    @Bean("tom")
    public Pet tom(){
        return new Pet("tomPet");
    }

    /**
     * 外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
     * @return
     */
    @ConditionalOnBean(name="tom") //springboot容器中存在tom组件的情况下才构建
    @Bean("user01")//给容器中添加组件,以方法名作为组件的id。返回类型就是组件类型。返回的值,就是存在组件中的实例
    public User user01(){

        User zhangsan = new User("zhangsan", 18);
        //proxyBeanMethods = true时,user组件依赖 Pet组件,SpringBoot
        zhangsan.setPet(tom());
        return zhangsan;
    }



}

 

你可能感兴趣的:(java,spring,boot,后端)