属性绑定
将容器中任意组件(Bean)的属性值和配置文件的配置项的值进行绑定
- 给容器中注册组件(
@Component
、@Bean
)- 使用
@ConfigurationProperties
声明组件和配置文件的哪些配置项进行绑定
场景:
SpringBoot
默认只扫描自己主程序所在的包。
如果导入第三方包,即使组件上标注了@Component
、@ConfigurationProperties
注解,也没用。
因为组件都扫描不进来,此时使用这个注解就可以快速进行属性绑定并把组件注册进容器
@ConfigurationProperties
@ConfigurationProperties
: 声明组件的属性和配置文件哪些 *前缀开始项
*进行绑定
package com.example.boot.Pojo;
@ConfigurationProperties(prefix = "pig") // 配置文件中的前缀
@Component
public class Pig {
private Long id;
private String name;
private Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Pig{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
server.port=8091
pig.id = 1
pig.name=佩奇
pig.age=5
@SpringBootConfiguration
public class AppConfig2 {
@Bean
// @ConfigurationProperties(prefix = "pig")
public Pig pig(){
return new Pig();
}
}
package com.example.boot;
import com.example.boot.Pojo.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Boot302DemoApplication {
public static void main(String[] args) {
var ioc = SpringApplication.run(Boot302DemoApplication.class, args);
Pig bean = ioc.getBean(Pig.class);
System.out.println(bean);
}
}
@EnableConfigurationProperties
@EnableConfigurationProperties
:快速注册注解:
package com.example.boot.Pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "sheep")
public class Sheep {
Long id;
String name;
Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Sheep{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
// 开启Sheep 的属性绑定,
// 默认会把这个组件直接放到容器中
@EnableConfigurationProperties(Sheep.class)
@SpringBootConfiguration
public class AppConfig2 {
}
sheep.id = 1
sheep.name=喜洋洋
sheep.age=5
package com.example.boot;
import com.example.boot.Pojo.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Boot302DemoApplication {
public static void main(String[] args) {
var ioc = SpringApplication.run(Boot302DemoApplication.class, args);
Sheep sheep = ioc.getBean(Sheep.class);
System.out.println(sheep);
}
}