• @ConfigurationProperties配置绑定~


    @ConfigurationProperties注解是Spring Boot中的一个注解,用于将配置文件中的属性值绑定到Java类中的字段上。

    @ConfigurationProperties注解的作用包括:

    1. 实现配置文件属性和Java类字段的映射,简化了读取配置文件的操作。

    2. 可以指定配置文件中的前缀,从而只绑定特定前缀的属性值。

    组件Car类:

    package com.springboot.bean;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Component
    @ConfigurationProperties(prefix = "mycar")
    public class Car {
        private String brand;
        private Integer price;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    控制器:

    package com.springboot.Controller;
    
    import com.springboot.bean.Car;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
        @Autowired
        Car car;
        @RequestMapping("/car")
        public Car car(){
            return car;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    application.properties:

    mycar.brand=byd
    mycar.price=100000
    
    • 1
    • 2

    启动类:

    package com.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    
    @SpringBootApplication
    
    public class MainApplication {
        public static void main(String[] args) {
          ConfigurableApplicationContext run= SpringApplication.run(MainApplication.class,args);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    浏览器显示如下所示:

    在这里插入图片描述

  • 相关阅读:
    多组学+机器学习+膀胱癌+分型+建模
    2024年火爆全网的三款ai智能直播系统,你知道哪一种?
    如何评价GPT-4o?
    【C语言】模拟实现strlen
    ASP.Net Core异步编程
    立体式校验保护,让你的系统避免 90% 以上的 bug
    2023NOIP A层联测9-紫罗兰
    C++零碎记录(九)
    强化学习笔记
    mock技术在测试中的应用
  • 原文地址:https://blog.csdn.net/m0_64365419/article/details/133557367