• SpringBoot中自动配置


    第一种:

            给容器中的组件加上

    @ConfigurationProperties注解即可

    测试:

    1. @Component
    2. @ConfigurationProperties(prefix = "mycar")
    3. public class Car {
    4. private String brand;
    5. private Integer price;
    6. private Integer seatNum;
    7. public Integer getSeatNum() {
    8. return seatNum;
    9. }
    10. public void setSeatNum(Integer seatNum) {
    11. this.seatNum = seatNum;
    12. }
    13. public String getBrand() {
    14. return brand;
    15. }
    16. public void setBrand(String brand) {
    17. this.brand = brand;
    18. }
    19. public Integer getPrice() {
    20. return price;
    21. }
    22. public void setPrice(Integer price) {
    23. this.price = price;
    24. }
    25. @Override
    26. public String toString() {
    27. return "Car{" +
    28. "brand='" + brand + '\'' +
    29. ", price=" + price +
    30. ", seatNum=" + seatNum +
    31. '}';
    32. }
    33. public Car() {
    34. }
    35. }

    在application.properties中属性:

    mycar.seatNum = 4
    mycar.brand = BMW
    mycar.price = 100000

    即可给之后new 的Car 对象自动配置。

    运行:

    1. public class MainApplication {
    2. public static void main(String[] args) {
    3. //返回springboot中的ioc容器
    4. ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
    5. Car car = run.getBean("car", Car.class);
    6. System.out.println(car);
    7. }
    8. }

    控制台结果:

     第二种:

            第一种的情况下是自己写的类作为组件,实现自动装配的过程;

            但有时候使用第三方类的时候无法将其设置为自己的组件,所以就需要用

    @EnableConfigurationProperties + @ConfigurationProperties

            将Car类删除@Component注解,此时Car类已经不是组件了:

             此时,假设Car是第三方提供的类:

            对于第三方的类 想要其作为组件就需要@Bean注解,就和之前的SSM项目中配置的bean

    标签一样:

            SSM中的配置文件中:

    1. <bean id="car" class="xxx.xxx.xxx.Car">
    2. <property name="brand" value=""/>
    3. <property name="price" value=" "/>
    4. <property name="seatNum" value=" "/>
    5. </bean>

            就等同于SpringBoot中配置类下的:

    1. @Bean
    2. public Car car(){
    3. Car car = new Car();
    4. return car;
    5. }

            其中属性的赋值就需要在Car类上增加

    @ConfigurationProperties(prefix = "mycar")注解

            最后在该配置类上使用

    @EnableConfigurationProperties(Car.class)注解开启即可
    1. @Configuration(proxyBeanMethods = false)
    2. @EnableConfigurationProperties(Car.class)
    3. public class CarAutoConfiguration {
    4. @Bean
    5. public Car car(){
    6. Car car = new Car();
    7. return car;
    8. }
    9. }

    控制台显示结果一样:

     

  • 相关阅读:
    模块化笔记软件综合评测:Craft、Notion、FlowUs
    模型量化笔记--KL散度量化
    分库分表理论总结
    2022值得一试的顶级 React 组件库
    精灵球Plus相关链接
    PaddleOCR学习笔记3-通用识别服务
    力扣26. 删除有序数组中的重复项
    MyBatis-Plus中的更新操作(通过id更新和条件更新)
    进阶JAVA篇-深入了解枚举与抽象枚举
    Java基础练习(矩阵的加减乘除运算)
  • 原文地址:https://blog.csdn.net/weixin_42196338/article/details/128090652