@ConfigurationProperties注解
- @ConfigurationProperties将配置文件的属性映射到实体类的属性上
- 有两个属性prefix和value,其实是一个属性可以通过两个其中一个去设值
- 还有ignoreInvalidFields属性默认为false,可设置为true,设置为true后赋值失败将不会启动失败
- 有三种用法
第一种
- 使用@ConfigurationProperties与@Component一起使用,相当与前缀.属性名
配置文件
server:
port: 9999
people:
name: "zhangsan"
age: 22
实体类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(value = "people")
public class People {
String name;
Integer age;
}
使用实体类
@RestController
public class yige {
@Autowired
People people;
@GetMapping("getName")
public void getName(){
System.out.println(people.getName());
System.out.println(people.getAge());
}
}
//结果
//zhangsan
//22
第二种
- 和Bean一起使用,对bean的属性进行赋值
配置文件
server:
port: 9999
people:
name: "xucanjie"
age: 22
student:
name: "xucanjie"
age: 22
实体类
import lombok.Data;
@Data
public class Student {
String name;
Integer age;
}
配置类
import com.xucanjie.pojo.Student;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
@Bean
@ConfigurationProperties(prefix = "student")
Student getStudent(){
return new Student();
}
}
验证
@RestController
public class yige {
@Autowired
People people;
@Autowired
Student student;
@GetMapping("getName")
public void getName(){
System.out.println(people.getName());
System.out.println(people.getAge());
wSocket.sendMessageTo(people.getName()+people.getAge());
}
@GetMapping("getStudent")
public Student getStudent(){
return student;
}
}
第三种
- 加在实体类上不适用@Comment,把@EnableConfigurationProperties加到启动类一起使用
配置类
server:
port: 9999
people:
name: "xucanjie"
age: 22
student:
name: "xucanjie"
age: 22
teacher:
name: "xucanjie"
age: 22
实体类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "teacher")
public class Teacher {
String name;
String age;
}
启动类
@SpringBootApplication
@EnableConfigurationProperties(Teacher.class)
public class XucanjieApplication {
public static void main(String[] args) {
SpringApplication.run(XucanjieApplication.class, args);
}
}
验证
@RestController
public class yige {
@Autowired
People people;
@Autowired
Student student;
@Autowired
Teacher teacher;
@GetMapping("getName")
public void getName(){
System.out.println(people.getName());
System.out.println(people.getAge());
}
@GetMapping("getStudent")
public Student getStudent(){
return student;
}
@GetMapping("getTeacher")
public Teacher getTeacher(){
return teacher;
}
}