当前位置:首页 > 编程笔记 > 正文
已解决

@ConfigurationProperties配置绑定~

来自网友在路上 156856提问 提问时间:2023-10-06 05:06:44阅读次数: 56

最佳答案 问答题库568位专家为你答疑解惑

@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;
}

控制器:

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 {@AutowiredCar car;@RequestMapping("/car")public Car car(){return car;}
}

application.properties:

mycar.brand=byd
mycar.price=100000

启动类:

package com.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;@SpringBootApplicationpublic class MainApplication {public static void main(String[] args) {ConfigurableApplicationContext run= SpringApplication.run(MainApplication.class,args);}
}

浏览器显示如下所示:

在这里插入图片描述

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"@ConfigurationProperties配置绑定~":http://eshow365.cn/6-16136-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!