原文网址:Spring--BeanFactoryPostProcessor的用法_IT利刃出鞘的博客-CSDN博客
简介
说明
本文介绍Spring的BeanFactoryPostProcessor的用法。
BeanPostProcessor和BeanFactoryPostProcessor的区别
项 | BeanPostProcessor | BeanFactoryPostProcessor |
处理的对象 | 处理Bean | 处理BeanFactory |
作用 | 在实例化Bean之后,修改Bean。 | 在实例化Bean之前,修改BeanDefinition。(BeanDefinition是Bean的信息,用于生成Bean)。 |
实例1:修改配置属性
原来的代码
Controller
package com.knife.example.controller;import com.knife.example.service.DemoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;@RestController
@Slf4j
public class HelloController {@Autowiredprivate DemoService demoService;@GetMapping("/test")public String test() {demoService.print();return "success";}
}
Service
package com.knife.example.service;import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Setter
@Component
public class DemoService {@Value("Tony")private String name;public void print() {System.out.println(name);}
}
测试:访问:
后端结果:
Tony
修改BeanDefinition
目标:修改DemoService里name这个配置属性,改为:Peter
注意:上边的DemoService要写Setter,否则这里无法修改其配置属性。
package com.knife.example.processor;import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {BeanDefinition beanDefinition = beanFactory.getBeanDefinition("demoService");MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();propertyValues.addPropertyValue("name", "Peter");}
}
测试:访问:http://localhost:8080/doc.html
后端结果
Peter
实例2:修改scope
见:自动启用@RefreshScope功能 - 自学精灵