SpringBoot两种绑定配置文件的方法

使用配置文件可以给类中的属性注入值。

配置文件(application.properties):

mycar.brand = BYD
mycar.price = 100000

 

 

控制器(controller):用于在网页上映射方法

@RestController //@RestContoller由 @Controller 和 @ResponseBody组成
         //@Controller告诉SpringBoot这是一个Controller,@ResponseBody使返回值显示在对应的网页上(SpringMVC),而不是html名
public class Controller { @Autowired //自动注入一个car Car car; @RequestMapping("/car") //映射到 /car 网页上 public Car car(){ return car; //输出car这个对象 } }

 

 

第一种方法:  在组件添加@ConfigurationProperties注解,注意不要加入构造器

@ConfigurationProperties(prefix = "mycar") //绑定配置文件,prefix是前缀,通过查找前缀来注入属性
@Component //必须声明为组件才可以使用
public class Car {
    private String brand; //属性
    private int price; //属性

    
public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", price=" + price + '}'; } }
//注:可以用LomBok中的 @ToString代替 toString方法,
// @Data代替Getter和Setter方法(也包括了toString),@AllArgsConstructor自动生成全参构造器,@NoArgsConstrucor 自动生成无参构造器
// 另外@Slf4j 可以增加一个日志,用log.info就可以向日志中输入内容

 第二种方法:把Car组件加入到配置类中,通过配置类把组件加入容器。

@Configuration //告诉SpringBoot这是个配置类
@EnableConfigurationProperties(Car.class) //1.开启Car配置绑定功能 //2.把Car这个组件自动注册到容器中 public class MyConfig {
... //里面啥也不用写
}

 

 然后Car类就可以把@Component删除,但是 @ConfigurationProperties这句不能变

 

主程序类不用变化,还是那几句。

 

posted @ 2021-11-11 15:02  Acc22222222  阅读(325)  评论(0)    收藏  举报