spring BeanPostProcessor後置處理器
阿新 • • 發佈:2018-12-12
這個介面有兩個方法:
public interface BeanPostProcessor { @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Nullable default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
類實現這個介面,spring每一個bean被建立時都會走這個介面的實現類,從而我們就可以加一下自己的邏輯,對spring中的bean做一些修改。
最好先了解一下spring的Bean的生命週期,我這簡化的說,在spring bean的生命週期中,就和servlet一樣,順序:建構函式例項化->注入屬性->setBeanName->setBeanFactory->postProcessAfterInitialization->afterPropertiesSet->init-method->postProcessBeforeInitialization,大體是這麼個流程。 所以我們可以在生命週期過程中,對bean做修改,完成自己的業務邏輯。
看下一個簡單的例子:
package com.xhx.spring.config; import com.xhx.spring.domain.User; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import java.net.UnknownServiceException; /** * xuhaixing * 2018/9/28 22:34 * 後置處理器 **/ @Configuration public class MyBeanPostProcessor implements BeanPostProcessor, Ordered { @Override public int getOrder() { return 0; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof User){ User user = (User)bean; user.setAge(18); } return bean; } }
在注入User類時,我把年齡給改了。
User bean的初始化:
package com.xhx.spring.config;
import com.xhx.spring.domain.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* xuhaixing
* 2018/9/28 22:31
**/
@Configuration
public class UserConfig {
@Bean
public User user(){
return new User("fdsf-df-32-fa-g","xu",25);
}
}
我們寫了一個介面,看一下User bean的值:
package com.xhx.spring.controller;
import com.xhx.spring.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* xuhaixing
* 2018/9/28 22:32
**/
@RestController
@RequestMapping(name = "user")
public class UserController {
@Autowired
private User user;
@RequestMapping(name = "getUser")
public User getUser(){
return user;
}
}