@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 { @Autowired Car 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; @SpringBootApplication public class MainApplication { public static void main(String[] args) { ConfigurableApplicationContext run= SpringApplication.run(MainApplication.class,args); } }
浏览器显示如下所示: