Spring Boot如何读取自定义外部属性详解

这篇文章主要给大家介绍了关于Spring Boot如何读取自定义外部属性的相关资料,这个功能实现介绍的很详细,需要的朋友可以参考下

测试的环境: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; } 

测试结果:

以上列举的不是全部方式,加载文件的方式还有其他方式,这篇只是列举常用的方式。

总结

到此这篇关于Spring Boot如何读取自定义外部属性的文章就介绍到这了,更多相关SpringBoot读取外部属性内容请搜索html中文网以前的文章或继续浏览下面的相关文章希望大家以后多多支持html中文网!

以上就是Spring Boot如何读取自定义外部属性详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java