springboot基础--配置文件

1.配置文件:

Springboot使用一个全局的配置文件,配置文件名是固定的。

  application.properties

  application.yml

使用配置文件的作用:修改springboot的自动配置的默认配置值

yml语法:

值的写法:

 

yml配置文件的值获取:

yml文件

server:
  port: 8082
person:
  lastname: 张三
  age: 21
  boss: true
  birth: 2020/12/22
  maps: {k1: a,k2: b,k3: c}
  lists: [lisi,wangnwu,小刘]
  dog:
    name: 小黑
    age: 3

配置文件的依赖

<!-- 配置文件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>

编写实体类,添加set get方法和toString方法:

注意:两个重要注解加上

@Component
@ConfigurationProperties("person")
@Component
@ConfigurationProperties("person")  //将配置文件映射到组件中,进行绑定
public class Person {
    private String lastname;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
public class Dog {
    private String name;
    private Integer age;

在测试类中测试结果

注意:添加@RunWith(SpringRunner.class)注解
springboot单元测试,可以在测试期间方便的注入容器进行测试
@RunWith(SpringRunner.class)
@SpringBootTest
class Demo2ApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}

 

Person{lastname='张三', age=21, boss=true, birth=Tue Dec 22 00:00:00 GMT+08:00 2020, maps={k1=a, k2=b, k3=c}, lists=[lisi, wangnwu, 小刘], dog=Dog{name='小黑', age=3}}

 

properties配置值的获取

#配置persond的值
#idea默认是utf-8,需要进行编码转换在file Encoding中设置
person.lastname=张三
person.age=21
person.boss=false
person.birth=2020/11/10
person.maps.k1=d
person.maps.k2=5
person.maps.k3=r
person.lists=c,f,g,h
person.dog.name=dog1
person.dog.age=5

 

中文编码问题

 

测试结果

Person{lastname='张三', age=21, boss=false, birth=Tue Nov 10 00:00:00 GMT+08:00 2020, maps={k1=d, k2=5, k3=r}, lists=[c, f, g, h], dog=Dog{name='dog1', age=5}}

 

 

posted @ 2020-11-10 09:36  lemmon_water  阅读(118)  评论(0)    收藏  举报