赞
踩
1.application.properties配置文件
- book.id=1
- book.name=我的老千生涯
- book.author=黑色枷锁
2.application.yml
- book:
- id: 2
- name: 我的老千江湖
- author: 黑色枷锁
3.application.yaml
- book:
- id: 3
- name: 新民间老八门
- author: 黑色枷锁
1.单属性注入@Value
- @Component
- public class Book {
- @Value("${book.id}")
- private Integer id;
- @Value("${book.name}")
- private String name;
- @Value("${book.author}")
- private String author;
-
- @Override
- public String toString() {
- return "Book{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", names='" + author + '\'' +
- '}';
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getAuthor() {
- return author;
- }
-
- public void setAuthor(String author) {
- this.author = author;
- }
- }
- @RestController
- public class HelloController {
- @Autowired
- private Book book;
-
- @RequestMapping("/book")
- public Book book() {
- return book;
- }
- }
页面结果:{"id":1,"name":"我的老千生涯","author":"黑色枷锁"}
2.Environment
- import com.example.demo.pojo.Book;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.core.env.Environment;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
-
- @RestController
- public class HelloController {
- @Autowired
- private Environment env;
-
- @RequestMapping("/book")
- public Book book() {
- System.out.println(env.getProperty("book.name"));
- return book;
- }
- }
控制台结果:我的老千生涯
使用时属性名与配置文件一致时才会被注入
prefix = "book"要被读取的上级名没有不写
- @Component
- @ConfigurationProperties(prefix = "book")
- public class Book {
- private Integer id;
- private String name;
- private String author;
-
- @Override
- public String toString() {
- return "Book{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", names='" + author + '\'' +
- '}';
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getAuthor() {
- return author;
- }
-
- public void setAuthor(String author) {
- this.author = author;
- }
- }
- @RestController
- public class HelloController {
- @Autowired
- private Book book;
- @RequestMapping("/book")
- public Book book() {
- return book;
- }
- }
页面结果:{"id":1,"name":"我的老千生涯","author":"黑色枷锁"}
使用@ConfigurationProperties会出现
不影响运行
加入依赖以上问题会解决并配置文件会有注入值提示但有可能会报前言中不允许有内容
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-configuration-processor</artifactId>
- </dependency>
这个时候只需要以下操作就可以解决这个问题
1.删除.idea
2.重启idea会自动创建一个新的.idea
3.这个时候就可以正常运行了
三种配置文件的读取方式注入方式一样
若三种配置文件同时存在读取优先级application.properties>application.yml>application.yaml
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。