SpringBoot 配置文件的使用 (properties yml)

   SpringBoot提供了 许多自动装配的功能,大大减少了开发的工作量,所以学习SpringBoot 也成了一门必修课。

   它的配置方式 与 之前的Spring有一定的不同。

   首先,它有两种配置的方式

  1.properties 的方式

  2.yml的方式

 配置流程:

1.写配置文件:

application.yml

server:
   port: 8888

student: 
  name: zs
  age: 23
  address:
   Provence: 陕西 
   #{Provence: 陕西}
  hobbies: [足球,篮球]
   #- 足球
   #- 篮球

此处注意 yml配置的方式 是 k:空格v

application.properties


server.port=8888
spring.thymeleaf.cache=true       
spring.devtools.restart.enabled=true  

student.name=zs

properties 则是k=v方式

2.第二步,就是绑定

@Component  //加入到spring 容器之中
@ConfigurationProperties(prefix = "student") //识别yml中的bean
@Validated //jsr303数据校验的开启
//@PropertySource(value = {"classpath:xxx.properties"}) //引入非默认文件的值 不能加载yml
public class student {
	@Email
	String email;
	
	String name;
	int age;
	Map<String,Object> address;
	List<String> hobbies;

/...省略 set get 构造方法.../
}

3.测试类   springboot 为我们提供了测试类

package com.cjr.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.cjr.demo.entity.student;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
//自动装配  与@Component 要对应
    @Autowired
	student student1;
	
	@Test
	public void contextLoads() {
		System.out.println(student1);
	}

}

发布了69 篇原创文章 · 获赞 5 · 访问量 2198

猜你喜欢

转载自blog.csdn.net/qq_42139889/article/details/104153937