千家信息网

Spring中怎么动态注册Bean

发表于:2026-11-02 作者:千家信息网编辑
千家信息网最后更新 2026年11月02日,这篇文章将为大家详细讲解有关Spring中怎么动态注册Bean,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。动态注册Bean到Spring容器是很简单
千家信息网最后更新 2026年11月02日Spring中怎么动态注册Bean

这篇文章将为大家详细讲解有关Spring中怎么动态注册Bean,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

动态注册Bean到Spring容器是很简单的,我们只要继承BeanDefinitionRegistryPostProcessor

@Componentpublic 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容器中管理。

@Mapperpublic interface UserMapper {        @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 findList(Class clazz, Query query);}
@Componentpublic 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  create(final Class 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;                    }                });    }}

关于Spring中怎么动态注册Bean就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

0