Spring中怎么动态注册Bean

发布时间:2021-06-21 16:27:38 作者:Leah
来源:亿速云 阅读:252

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

动态注册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;
                    }
                });
    }
}

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

推荐阅读:
  1. Spring运行时动态注册bean的方法
  2. 使用Spring怎么动态注册bean

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring bean

上一篇:idea中怎么导入多module项目

下一篇:Linux中怎么实现nginx日志文件切分

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》