SpringBoot获取配置信息的三种方式总结
作者:秋日的晚霞
这篇文章给大家介绍了SpringBoot获取配置信息的三种方式,@Value属性值注入,绑定配置类和通过 environment获取这三种方式,文中通过代码示例给大家介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
Spring获取配置信息的三种方式
1. @Value属性值注入
@Value("${student.name}") private String name; public static void main(String[] args) { SpringApplication.run(SpringConfigDemoApplication.class, args); } @PostConstruct private void init() { System.out.println("name = " + name); }
2. 绑定配置类
@ConfigurationProperties(prefix = "student") public class StudentProperties { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
@EnableConfigurationProperties(StudentProperties.class) @SpringBootApplication public class SpringConfigDemoApplication { @Value("${student.name}") private String name; @Autowired private StudentProperties studentProperties; public static void main(String[] args) { SpringApplication.run(SpringConfigDemoApplication.class, args); } @PostConstruct private void init() { System.out.println("name1 = " + name); } @PostConstruct private void init2() { System.out.println("name2 = " +studentProperties.getName()); } }
3. 通过 environment 获取
package com.sz.springconfigdemo; import com.sz.springconfigdemo.properties.StudentProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import javax.annotation.PostConstruct; @EnableConfigurationProperties(StudentProperties.class) @SpringBootApplication public class SpringConfigDemoApplication { @Value("${student.name}") private String name; @Autowired private StudentProperties studentProperties; @Autowired private Environment environment; public static void main(String[] args) { SpringApplication.run(SpringConfigDemoApplication.class, args); } @PostConstruct private void init() { System.out.println("name1 = " + name); } @PostConstruct private void init2() { System.out.println("name2 = " +studentProperties.getName()); } @PostConstruct private void init3() { String environmentProperty = environment.getProperty("student.name"); System.out.println("name3 = " +environmentProperty); } }
以上就是SpringBoot获取配置信息的三种方式总结的详细内容,更多关于SpringBoot获取配置信息的资料请关注脚本之家其它相关文章!