Python 官方文档:入门教程 => 点击学习
创建实体类 @Data public class Cat { private String name; private Integer age; } @Data pu
创建实体类
@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();
}
}
总结:
到此这篇关于SpringBoot bean依赖属性配置详细介绍的文章就介绍到这了,更多相关SpringBoot bean依赖属性配置内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: SpringBootbean依赖属性配置详细介绍
本文链接: https://lsjlt.com/news/168452.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0