原文網址: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功能 - 自學精靈