动态注册Bean到Spring容器是很简单的,我们只要继承BeanDefinitionRegistryPostProcessor
@Component
public class TestDynamicRegistBean implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("yzy:TestDynamicRegistBean.postProcessBeanDefinitionRegistry");
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(User.class);
beanDefinition.getPropertyValues().add("name", "yangzhongyu");
registry.registerBeanDefinition("user", beanDefinition);
}
}
还可以重载postProcessBeanFactory来完成同样的事情,注册User user 到Spring容器。
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException{
System.out.println("yzy:TestDynamicRegistBean.postProcessBeanFactory");
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(User.class);
beanDefinition.getPropertyValues().add("age", "yangzhongyu");
((DefaultListableBeanFactory) beanFactory)
.registerBeanDefinition("user", beanDefinition);
}
MyBatis,Dubbo等采用了这个技术来实现Bean的动态注册.
在MyBatis中我们定义的Mapper本质上只是一个Java的普通接口,那么是如何交给到Spring容器管理的呢?
其中的原理就是通过CGLib或者JDK动态代理动态生成了Mapper接口的子类,并且通过Spring的动态注册机制实例化对象.
beanFactory.registerSingleton把创建好的对象放入Spring容器中管理。
@Mapper
public interface UserMapper<T> {
@InsertProvider(type = SqlFactory.class, method = "insert")
@Options(useGeneratedKeys = true)
Boolean insert(T data);
@UpdateProvider(type = SqlFactory.class, method = "update")
Boolean update(T data);
@SelectProvider(type = SqlFactory.class, method = "find")
T find(Class clazz, Query query);
@SelectProvider(type = SqlFactory.class, method = "find")
List<T> findList(Class clazz, Query query);
}
@Component
public class MapperRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerSingleton("userMapper", create(UserMapper.class));
}
private <T> T create(final Class<T> interfaceClazz) {
return (T) Proxy.newProxyInstance(interfaceClazz.getClassLoader(),
new Class<?>[]{interfaceClazz}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// String respone = (String) method.invoke(proxy, args);
boolean isMapper = interfaceClazz.isAnnotationPresent(Mapper.class);
if(isMapper){
Method[] methods = interfaceClazz.getDeclaredMethods();
for(Method m : methods){
if(m.isAnnotationPresent(SelectProvider.class)){
//通过JDBC执行SQL把结果返回
}else if(m.isAnnotationPresent(UpdateProvider.class)){
}else if(m.isAnnotationPresent(InsertProvider.class)){
}else if(m.isAnnotationPresent(DeleteProvider.class)){
}
}
}
System.out.println("method="+method.getName());
return 0;
}
});
}
}