bean依赖属性配置
文章目录
- bean依赖属性配置
@Data
@ConfigurationProperties(prefix = "cartoon")
public class CartoonProperties {private Cat cat;private Mouse mouse;
}
cartoon:cat:name: whatage: 5mouse:name: howage: 6
这样的话,业务bean无需在读取配置文件的操作了。
EnableConfigurationProperties来设置关联,在使用时加载bean,不用时不加载
@EnableConfigurationProperties(CartoonProperties.class)//关联注解 强制设置哪一个类成为bean
@Data
public class CartoonCatAndMouse {private Cat cat;private Mouse mouse;@Autowiredprivate 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
@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