Spring Boot的配置文件以及获取配置文件中的值

Spring boot配置文件
Spring Boot使用一个全局的配置文件application.properties或application.yml
配置文件可以放置在src/main/resources目录或者类路径的/config下
Spring Boot不仅支持常规的properties文件,而且还支持yaml语言的配置文件。Yaml是以数据为中心的语言,在配置数据的时候具有面向对象的特性。
修改端口号:
application.properties中

server.port=8081

在application.yml文件中

server:
  port: 8081

yaml的基本语法
key:(空格)value:表示一对键值对(空格必须有);
以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的
配置文件的作用
对Spring boot自动配置的默认值进行修改

获取配置文件中的值
application.xml

book.id=1
book.bookname=spring boot in action
book.price=69.99

1、使用@Value("${key}")注解来获取、

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloSpringBootApplicationTests {
	@Value("book.bookname")
	private String bookname;
	@Test
	public void contextLoads() {
		System.out.println(name);
	}
}

2、Environment,env.getProperty(“键名”)

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloSpringBootApplicationTests {
	@Autowired
	private Environment environment;
	@Test
	public void contextLoads() {
		System.out.println(environment.getProperty("book.bookname"));
	}
}

3、使用ConfigurationProperties来获取
@ConfigurationProperties:告诉spring boot将本类中的所有属性和配置文件中的配置进行绑定
prefix=“book” 映射配置文件中book下的所有属性
只有这个Bean是容器中的Bean,才能使用容器提供的@ConfigurationProperties功能;所以给Book添加@Component。
@ConfigurationProperties默认从全局配置文件中获取值,可以使用@PropertySource(value={“classpath:/config/book.properties”})来加载指定的配置文件

@Data
@Component
@PropertySource(value={"classpath:/config/book.properties"})
@ConfigurationProperties(prefix="book")
public class Book implements Serializable{
	private static final long serialVersionUID = 1L;
	@Setter
	private Integer id;
	@Setter
	private String bookname;
	@Setter
	private double price;
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloSpringBootApplicationTests {
	@Autowired
	private Book book;
	@Test
	public void contextLoads() {
		System.out.println(book);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_27046951/article/details/82752534