配置文件
两中配置文件格式不同,采用的书写语法也不同。
Yaml 语法更更加简洁,properties 使⽤用更更加⼴广泛
- application.properties
- application.yml
把创建好的工程中的application.properties重命名成application.yml
blog:
title: 蜡笔小新
desc: 这是关系蜡笔小新的故事
测试读取单个值
package com.chen.springbootproperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
@Value("${blog.title}")
private String title;
@Test
public void testGetTitle(){
System.out.println(title);
}
}
测试读取多个配置:
新建配置类MyConstant
package com.chen.springbootproperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "blog")
public class MyConstant {
private String title;
private String desc;
}
注入资源,获取配置文件的内容
package com.chen.springbootproperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
@Resource
private MyConstant myConstant;
@Test
public void testMyConstant(){
System.out.println(myConstant.getTitle());
System.out.println(myConstant.getDesc());
}
}
自定义配置文件
新建other.properties文件
other.title=this is title
other.desc=this is desc
新建配置类
package com.chen.springbootproperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "other")
@PropertySource("classpath:other.properties")
public class OtherProperties {
private String title;
private String desc;
}
测试类
package com.chen.springbootproperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
@Resource
private OtherProperties otherProperties;
@Test
public void testOtherProperties(){
System.out.println(otherProperties.getTitle());
System.out.println(otherProperties.getDesc());
}
}
测试结果: