SpringBoot bean依赖属性配置详细介绍

Spring容器是Spring的核心,一切SpringBean都存储在Spring容器内。可以说bean是spring核心中的核心。Bean配置信息定义了Bean的实现及依赖关系,这篇文章主要介绍了SpringBootbean依赖属性配置

创建实体类

@Data
public class Cat {
    private String name;
    private Integer age;
}
@Data
public class Mouse {
    private String name;
    private Integer age;
}

配置文件application.yml使用固定格式为属性注入数据

cartoon:
  cat:
    name: "图多盖洛"
    age: 5
  mouse:
    name: "泰菲"
    age: 6

业务类定义业务功能bean,在引导类通常使用@Import导入,解耦强制加载bean

使用@EnableConfigurationProperties注解设定使用属性类时加载bean

@Data
//当加载CartoonCatAndMouse类时将CartoonProperties类加载成bean,不用不加载,解耦合
@EnableConfigurationProperties(CartoonProperties.class)
public class CartoonCatAndMouse {
    private Cat cat;
    private Mouse mouse;
    private CartoonProperties cartoonProperties;
    public CartoonCatAndMouse(CartoonProperties cartoonProperties){
        this.cartoonProperties = cartoonProperties;
        cat = new Cat();
        cat.setName(cartoonProperties.getCat()!=null && StringUtils.hasText(cartoonProperties.getCat().getName()) ? cartoonProperties.getCat().getName() : "tom");
        cat.setAge(cartoonProperties.getCat()!=null && cartoonProperties.getCat().getAge()!=null ? cartoonProperties.getCat().getAge() : 3);
        mouse = new Mouse();
        mouse.setName(cartoonProperties.getMouse()!=null && StringUtils.hasText(cartoonProperties.getMouse().getName()) ? cartoonProperties.getMouse().getName() : "jerry");
        mouse.setAge(cartoonProperties.getMouse()!=null && cartoonProperties.getMouse().getAge()!=null ? cartoonProperties.getMouse().getAge() : 4);
 
    }
    public void play(){
        System.out.println(cat.getAge()+"岁的"+cat.getName()+"和"+ mouse.getAge()+"岁的"+mouse.getName()+"打起来了");
    }
}

将业务功能bean运行需要的资源抽取长独立的属性类,设置读取配置文件的信息

@Data
//类与配置文件绑定
@ConfigurationProperties(prefix = "cartoon")
public class CartoonProperties {
    private Cat cat;
    private Mouse mouse;
}

测试:

@SpringBootApplication
//当运行时将CartoonCatAndMouse类加载成bean,不允许不加载
@Import(CartoonCatAndMouse.class)
public class Demo15SpringbootBeanpropertiesApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Demo15SpringbootBeanpropertiesApplication.class, args);
        CartoonCatAndMouse bean = ctx.getBean(CartoonCatAndMouse.class);
        bean.play();
    }
}

总结:

  1. 业务bean的属性可以为其设定默认值
  2. 当需要设置时通过配置文件传递属性
  3. 业务bean应尽量避免设置强制加载,而是根据需要导入后加载,降低spring容器管理bean的强度

到此这篇关于SpringBoot bean依赖属性配置详细介绍的文章就介绍到这了,更多相关SpringBoot bean依赖属性配置内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!

本文标题为:SpringBoot bean依赖属性配置详细介绍

基础教程推荐