在springboot出现之前,spring一般都是通过读取我们编写的xml文件来创建Bean的,在<Bean>标签中我们需要定义Bean的类型以及属性等有关于描述Bean的信息,BeanFactory就是通过这些信息来定义一个Bean的,在Bean初始化的过程中,Bean的属性都会被赋予对应类型的默认值,比如,String类型属性默认值就是null,一般引用类型的默认值都是null。那有没有办法不让Bean的某个属性不去默认值而取我们自定义的值呢?答案是BeanFactoryPostProcessor后置处理器,该处理器的作用是在Bean初始化之前也就是调用构造方法之前给对应的属性赋值。这样就可以在Bean初始化调用构造方法时传递我们赋值。测试用例如下:
@Component
public class Student {
private String name;
private Integer age;
private String phone;
public Student() {
System.out.println("无参构造初始化");
}
public Student(String name, Integer age, String phone) {
System.out.println("全参构造初始化");
this.name = name;
this.age = age;
this.phone = phone;
}
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;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
@Component
public class CustomeBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
System.out.println("CustomeBeanFactoryPostProcessor开始改变默认值");
BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition("student");
beanDefinition.getPropertyValues().add("name","I'm an cool boy");
System.out.println("CustomeBeanFactoryPostProcessor结束改变默认值");
}
}
@RestController
public class StudentController {
@Autowired
private Student student;
@GetMapping("/get")
public Student getStudent(){
return student;
}
}