在前面的文章中,我们使用spring boot默认的配置文件application.properties配置数据库连接信息。本文我们将介绍spring boot常用的两种读取配置文件的方式以及自定义配置文件。
数据类型
基本类型,如:
#基本类型
person.name=zhangsan
person.age=18
#List(set、数组)类型,如:
person.hobbies[0]=\u6253\u7403
person.hobbies[1]=\u770b\u7535\u5f71
#Map类型,如
person.key.id=66666666666
使用@Value(“${属性名}”)映射配置属性
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;
使用注解@ConfigurationProperties映射
package com.example.demo.controller;
import com.example.demo.property.Person;
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;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yuxl on 2019/1/21.
*/
@RestController
public class PropertyController {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;
@RequestMapping("/properties")
public String getProperties(){
return "name: " + name + " ,age: " + age ;
}
@Autowired
private Person person;
@RequestMapping("/configProperties")
public String getConfigProperties(){
return "name: " + person.getName() + " ,age: "
+ person.getAge() + " ,hobbies: "
+ person.getHobbies().toString()
+ " ,key: " + person.getKey().toString();
}
}
自定义配置文件
如果使用自定义的配置文件,方法同使用注解@ConfigurationProperties映射,只不过在映射类上多加一个注解注明自定义配置文件路径
@Configuration
@PropertySource(“classpath:person.properties”)
@ConfigurationProperties(prefix = “person”)
写个controller文件进行测试
PropertyController.java
package com.example.demo.controller;
import com.example.demo.property.Person;
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;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yuxl on 2019/1/21.
*/
@RestController
public class PropertyController {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;
@RequestMapping("/properties")
public String getProperties(){
return "name: " + name + " ,age: " + age ;
}
@Autowired
private Person person;
@RequestMapping("/configProperties")
public String getConfigProperties(){
return "name: " + person.getName() + " ,age: "
+ person.getAge() + " ,hobbies: "+ person.getHobbies().toString()
+ " ,key: " + person.getKey().toString();
}
}
结果输出:
感谢大家百忙之中抽出宝贵的时间阅读本文,欢迎大家批评指正。微信扫下面二维码添加公众号议码评川,可获取java web、大数据、人工智能等相关学习资料。