springboot读取配置文件的方式
1.通过@ConfigurationProperties(prefix = “com.sun”)注解作用在方法上
配置文件内容
com:
sun:
name: "暗夜"
age: 18
sun1:
name: "第二个人"
age: 19
首先我们定义一个类
@Data
public class Person {
private String name;
private int age;
}
建一个配置类
@Configuration
public class PersonConfig {
@Bean
//给定配置文件中需要注入属性的前缀 通过set get方法注入
@ConfigurationProperties(prefix = "com.sun")
public Person person(){
return new Person();
}
}
搞一个测试类
@SpringBootTest
class PersonTest {
@Autowired
private Person person;
@Test
public void fun(){
System.out.println(person);//打印Person(name=暗夜, age=18)
}
}
方案二
直接在类上使用@ConfigurationProperties注解并指定前缀
@Data
@ConfigurationProperties(prefix = "com.sun1")
public class Person {
private String name;
private int age;
}
在配置类中使用 @EnableConfigurationProperties(Person.class)注解 将使用@ConfigurationProperties的类注册到spring中
@Configuration
@EnableConfigurationProperties(Person.class)
public class Person2Config {
@Bean
public Person person2(){
return new Person();
}
}
测试
@SpringBootTest
class PersonTest {
@Autowired
private Person person;
@Autowired
@Resource(name = "person2")//通过name注入bean
private Person person2;
@Test
public void fun(){
System.out.println(person);//Person(name=暗夜, age=18)
System.out.println(person2);//Person(name=第二个人, age=19)
}
}
最后两个的测试成功
总结
使用@ConfigurationProperties注解作用在方法上时可直接使用
作用在类上的时候时 需要通过@EnableConfigurationProperties(##.class)在配置类中向spring ioc注册该类的bean