Spring 框架提供了許多接口,可使用這些接口來定製化 bean ,而非簡單的 getter/setter 或者構造器注入。細翻 Spring Cloud Netflix、Spring Cloud Alibaba 等這些構建在 Spring Framework 的成熟框架源碼,你會發現大量的擴展 bean 例如html
package org.springframework.cloud.netflix.eureka;
public class EurekaHealthCheckHandler implements InitializingBean {}
複製代碼
package com.alibaba.cloud.seata.feign;
public class SeataContextBeanPostProcessor implements BeanPostProcessor {}
複製代碼
@Slf4j
public class DemoBean implements InitializingBean {
public DemoBean() {
log.info("--> instantiate ");
}
@PostConstruct
public void postConstruct() {
log.info("--> @PostConstruct ");
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("--> InitializingBean.afterPropertiesSet ");
}
public void initMethod() {
log.info("--> custom initMehotd");
}
}
複製代碼
@Configuration
public class DemoBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if ("demoBean".equals(beanName)){
log.info("--> BeanPostProcessor.postProcessBeforeInitialization ");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if ("demoBean".equals(beanName)){
log.info("--> BeanPostProcessor.postProcessAfterInitialization ");
}
return bean;
}
}
複製代碼
@Configuration
public class DemoConfig {
@Bean(initMethod = "initMethod")
public DemoBean demoBean() {
return new DemoBean();
}
}
複製代碼
DemoBean : --> instantiate
DemoBeanPostProcessor: --> BeanPostProcessor.postProcessBeforeInitialization
DemoBean : --> @PostConstruct
DemoBean : --> InitializingBean.afterPropertiesSet
DemoBean : --> custom initMehotd
DemoBeanPostProcessor: --> BeanPostProcessor.postProcessAfterInitialization
複製代碼
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 執行BeanPostProcessor.postProcessBeforeInitialization
Object wrappedBean = wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
...
// 執行用戶自定義初始化and JSR 250 定義的方法
invokeInitMethods(beanName, wrappedBean, mbd);
...
// 執行執行BeanPostProcessor.postProcessAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean;
}
複製代碼
BeanPostProcessor 是一個能夠自定義實現回調方法接口,來實現本身的實例化邏輯、依賴解決邏輯等,若是想要在 Spring 完成對象實例化、配置、初始化以後實現本身的業務邏輯,能夠經過擴展實現一個或多個 BeanPostProcessor 處理。java
// seata 上下文轉換,將其餘類型 wrap 成 SeataFeignContext
public class SeataContextBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName){
if (bean instanceof FeignContext && !(bean instanceof SeataFeignContext)) {
return new SeataFeignContext(getSeataFeignObjectWrapper(),
(FeignContext) bean);
}
return bean;
}
}
複製代碼
net.dreamlu.mica.redisson.stream.RStreamListenerDetector 查找自定義 @RStreamListener 實現 基於 Redisson 的 pub/sub
public class RStreamListenerDetector implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> userClass = ClassUtils.getUserClass(bean);
ReflectionUtils.doWithMethods(userClass, method -> {
RStreamListener listener = AnnotationUtils.findAnnotation(method, RStreamListener.class);
.... do something
}, ReflectionUtils.USER_DECLARED_METHODS);
return bean;
}
}
複製代碼
JavaEE5 引入了@PostConstruct 做用於 Servlet 生命週期的註解,實現 Bean 初始化以前的自定義操做。git
這裏須要注意的 這個註解不是 Spring 定義的,而是屬於 JavaEE JSR-250 規範定義的註解,當你在使用 Java11 的時候要手動引入相關 jar(由於 Java11 移除了)github
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
複製代碼
使用場景: 在以前的版本,咱們能夠在啓動後經過 @PostConstruct 註解的方法執行初始化數據。但因爲 Java 高版本已經移除相關 API ,咱們不推薦使用此 註解,能夠經過 Spring 相關 Event 回調事件處理redis
@PostConstruct 註解的方法在項目啓動的時候執行這個方法,也能夠理解爲在 spring 容器啓動的時候執行,可做爲一些數據的常規化加載,好比數據字典之類的。spring
InitializingBean 接口方法會在 容器初始化(getter/setter/構造器)完成 bean 的屬性注入後執行。api
應用場景: 動態修改容器注入的 Bean 參數bash
security:
oauth2:
ignore-urls:
- '/ws/**'
@ConfigurationProperties(prefix = "security.oauth2")
public class PermitAllUrlProperties {
@Getter
@Setter
private List<String> ignoreUrls = new ArrayList<>();
}
複製代碼
@ConfigurationProperties(prefix = "security.oauth2.ignore")
public class PermitAllUrlProperties implements InitializingBean {
@Getter
@Setter
private List<String> urls = new ArrayList<>();
@Override
public void afterPropertiesSet() {
urls.add("/common/*");
}
}
複製代碼
上文 @PostConstruct 已經不推薦你們使用,可使用 Bean(initMethod = 'initMehotd') 替代,相關的限制如上。app
@Bean(initMethod = "initMethod")
public DemoBean demoBean() {
return new DemoBean();
}
public void initMethod() {
log.info("--> custom initMehotd");
}
複製代碼