一、创建SpringBoot项目
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!--spring-boot-starter-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--导入配置文件处理器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
二、编写Bean及配置文件
1.配置文件
application.yml
person:
name: 古力娜扎
age: 27
2.Bean类
只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能,将配置文件中配置的每一个属性的值,映射到这个组件中
@ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定 ,prefix = "person":配置文件中哪个下面的属性进行一一映射
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// set、get方法
}
三、测试
@SpringBootApplication
public class SpringBootHahaApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringBootHahaApplication.class, args);
Person person = context.getBean(Person.class);
System.out.println(person);
}
}
结果: