测试的环境:Spring Boot2 + Maven +lombok
准备需要用到的基础类:
public class People {
private String name;
private String address;
private String phone;
}
准备默认的配置文件application.properties,内容如下
people.default.name=zs
people.default.address=ccc
people.default.phone=122122
准备自定义配置文件people.properties,内容如下
people.default.name=test-zs
people.default.address=test-address
people.default.phone=111111
准备测试类
@RestController
public class PeopleController {
@Autowired
private People people;
@RequestMapping("/test1")
public void test1(){
System.out.println(people);
}
}
第一种情况:读取默认配置文件中的自定义属性(如application.properties)
1、直接在指定类读取文件属性
@Data
//@Setter
@ToString
@Configuration
@ConfigurationProperties(prefix = "people.default")
public class People {
private String name;
private String address;
private String phone;
}
测试结果:
注意:类用到了lombok的注解(@Data)或者使用@Setter注解。所以有getter/setter。如果没有使用注解,则需要setter方法才能读取成功。
2、配合@Vaule读取文件属性
@Configuration
public class PeopleConfigrution {
@Value("${people.default.name}")
private String name;
@Value("${people.default.address}")
private String address;
@Value("${people.default.phone}")
private String phone;
@Bean
public People initPeople(){
People people=new People();
people.setName(name);
people.setPhone(phone);
people.setAddress(address);
return people;
}
}
测试结果:
3、使用Environment读取
@Configuration
public class PeopleConfigrution {
@Autowired
private Environment environment;
@Bean
public People initPeople(){
People people=new People();
people.setName(environment.getProperty("people.default.name"));
people.setPhone(environment.getProperty("people.default.phone"));
people.setAddress(environment.getProperty("people.default.address"));
return people;
}
}
测试结果:
第二种情况:读取自定义文件中的属性(如people.properties)
需指定读取文件的位置,可使用@PropertySource
注解指定,如
@Data
//@Setter
@ToString
@Configuration
@PropertySource("classpath:people.properties") //指定读取文件位置,可与读取默认文件第一种方式相比。
@ConfigurationProperties(prefix = "people.default")
public class People {
private String name;
private String address;
private String phone;
}
测试结果:
以上列举的不是全部方式,加载文件的方式还有其他方式,这篇只是列举常用的方式。