Spring Boot数据获取
简单来说,数据获取就是从application.yml配置文件中拿到相对应的值然后交给对应的实体类对象的属性。
SpringBoot 提供了以下3种注解来获取数据:
@Value
@Environment
@ConfigurationProperties
1. @Value
当我们需要获取配置文件中的某一个数据时,就可以通过 @Value 注解来获取。(使用时标注在实体类的属性上)
application.yml person: name: lucy age: 18 hobby: - basketball - music - dance name1: tony msg1: 'hello \n springboot!' msg2: "hello \n SpringBoot!"
@Value("${name1}") String name1; @Value("${person.name}") String name; @Value("${person.age}") int age; @Value("${person.hobby[0]}") String hobby; @Value("${msg1}") String msg1; @Value("${msg2}") String msg2;
输出结果如下:
2. @Environment
引入Environment
通过getProperty方法来获取数据
@RestController public class HelloController { @Autowired private Environment environment; @RequestMapping("/hello") public String hello(){ System.out.println("name1:"+ environment.getProperty("name1")); System.out.println("name:"+ environment.getProperty("person.name")); System.out.println("age:"+ environment.getProperty("person.age")); System.out.println("hobby:"+ environment.getProperty("person.hobby[1]")); System.out.println("msg1:"+ environment.getProperty("msg1")); System.out.println("msg2:"+ environment.getProperty("msg2")); return "Hello Spring Boot!"; } }
获取结果:
3. @ConfigurationProperties
@ConfigurationProperties主要作用就是将prefix属性指定的前缀配置项的值绑定到这个JavaBean上,需要和@Component或者@Configuration一起使用才能生效。(使用时标注在实体类上)
创建一个Person.java的实体类
@Component @ConfigurationProperties(prefix = "person") public class Person { private String name; private int age; private String[] hobby; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", hobby=" + Arrays.toString(hobby) + '}'; } }
当出现下面的错误时,需要在pom.xml文件中添加下面的依赖(没有就忽略)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
编写一个控制器方法
@RestController public class HelloController { @Autowired private Person person; @RequestMapping("/person") public Person person(){ return person; } }
启动该项目,访问地址:http://localhost:8081/person