Spring Boot有两中类型的配置文件:.properties和.yml。Spring Boot默认的全局配置文件名为application.properties或者application.yml(spring官方推荐使用的格式是.yml格式,目前官网都是实例都是使用yml格式进行配置讲解的),应用启动时会自动加载此文件,无需手动引入。web
我自定义一个配置文件my.propertiesspring
student.name = ZhangSan student.age = ${random.int[1,30]} student.parents[0] = ZhangMing student.parents[1] = XiaoHua
建立一个Bean,用于自动读取配置文件的内容(注:需保证与配置文件的字段一致)springboot
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.List; /** * Created by Administrator on 2018/9/28. */ @Component @PropertySource(value = "classpath:/my.properties", encoding="utf-8") //设置系统加载自定义的配置文件,并指定配置文件编码格式 @ConfigurationProperties(prefix = "student") @Data public class Student { private String name; private int age; private List<String> parents; }
import com.jc.testConf.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by Administrator on 2018/6/26. */ @RestController public class HelloController { @Autowired Student student; @RequestMapping("/testConf") private String getStudent(){ return student.toString(); } }
测试,果真可以获取到配置文件的数据
因此,之后,就可经过配置对象来获取相关的配置便可。app
import com.jc.testConf.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by Administrator on 2018/6/26. */ @RestController public class HelloController { @Value(value = "${student.name}") String name; @RequestMapping("/studentName") private String studentName(){ return name; } }
测试能够获取
dom
在学习配置中,设计到其余的知识点,全部在文章末尾补充下。学习
有三种使用方式:测试
https://blog.lqdev.cn/2018/07/14/springboot/chapter-third/
http://blog.51cto.com/4247649/2118348编码