最近在看spring集成mybatis的代码,发现MapperScannerConfigurer实现了BeanDefinitionRegistryPostProcessor接口:
很好奇BeanDefinitionRegistryPostProcessor有什么作用呢,看看MapperScannerConfigurer中postProcessBeanDefinitionRegistry方法的调用关系:
原来是在org.springframework.context.support.AbstractApplicationContext#refresh
方法中调用的:
//Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
该方法是让我们自定义的注册bean,下面来实现自定义bean并注册到BeanDefinitionRegistry:
/**
* @author LiosWong
* @description
* @date 2018/9/5 下午10:14
*/
@Component
public class TestPostProcessorRegistration implements BeanDefinitionRegistryPostProcessor{
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
//创建BeanDefinitionBuilder
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(UserInfoEntity.class);
//设置属性值
builder.addPropertyValue("name","list_test");
//设置可通过@Autowire注解引用
builder.setAutowireMode(AUTOWIRE_BY_NAME
//注册到BeanDefinitionRegistry
registry.registerBeanDefinition("userInfoEntity",builder.getBeanDefinition());
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
Test:
@RestController
public class OkController {
@Autowired
UserInfoEntity userInfoEntity;
@GetMapping(value = "/ok")
public String ok(){
return userInfoEntity.getName();
}
返回的是lios_test,至此完成了自定义bean并成功使用了。