bean依赖属性配置

bean依赖属性配置

文章目录

java 复制代码
@Data
@ConfigurationProperties(prefix = "cartoon")
public class CartoonProperties {
    private Cat cat;
    private  Mouse mouse;
}
java 复制代码
cartoon:
  cat:
    name: what
    age: 5
  mouse:
    name: how
    age: 6

这样的话,业务bean无需在读取配置文件的操作了。

EnableConfigurationProperties来设置关联,在使用时加载bean,不用时不加载

java 复制代码
@EnableConfigurationProperties(CartoonProperties.class)//关联注解 强制设置哪一个类成为bean
@Data
public class CartoonCatAndMouse {
    private Cat cat;
    private  Mouse mouse;

    @Autowired
    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() + "打起来了");
    }
}

也可以把业务类的@Component注解取消

启动时,添加注解@Import(CartoonCatAndMouse.class),根据需要来配置bean

java 复制代码
@SpringBootApplication
@Import(CartoonCatAndMouse.class)
public class Springboot29BeanPropertiesApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Springboot29BeanPropertiesApplication.class, args);
        CartoonCatAndMouse bean = ctx.getBean(CartoonCatAndMouse.class);
        bean.play();
    }

}

视频链接:

https://www.bilibili.com/video/BV15b4y1a7yG/?p=155\&spm_id_from=pageDriver\&vd_source=f6debc5a79e3f424f9dde2f13891b158

相关推荐
ok!ko1 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
2401_857622661 小时前
SpringBoot框架下校园资料库的构建与优化
spring boot·后端·php
2402_857589361 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰2 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
哎呦没2 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
_.Switch3 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
编程、小哥哥3 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
IT学长编程4 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
莹雨潇潇4 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
杨哥带你写代码4 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端