spring 中如何动态地创建 bean ?

14 篇文章 0 订阅
2 篇文章 0 订阅

一、目的

我需要扫描指定 package 下的 service 类,并且调用工厂方法创建 bean 实例。

二、方法

spring 提供了几种定义bean的方法:

  • 静态定义方式,用 <bean> 标签
  • static-factory-method 方式,用 factory-method 属性
  • instance-factory-method 方式,用 factory-beanfactory-method 属性

但是这里我们在调用 factory-method 的时候需要传递一个参数,指明 service 类。所幸,spring 支持带参数的 factory-method 调用。

spring 文档:

Arguments to the static factory method are supplied via elements, exactly the same as if a constructor had actually been used. The type of the class being returned by the factory method does not have to be of the same type as the class that contains the static factory method, although in this example it is. An instance (non-static) factory method would be used in an essentially identical fashion (aside from the use of the factory-bean attribute instead of the class attribute), so details will not be discussed here.

成功的代码如下:

    /**
     * Scan and register service beans.
     * @param registry
     * @throws BeansException
     */
    @Override
    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        Class[] serviceClasses = scanServiceClasses()
        for (Class serviceClass in serviceClasses) {
            String serviceBeanName = serviceClass.getSimpleName().uncapitalize()
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(serviceClass)
            // 设置 instance factory method and argument
            beanDefinitionBuilder.setFactoryMethodOnBean('createServiceInstance', name)
            beanDefinitionBuilder.addConstructorArgValue(serviceClass)
            // 设置依赖
            // beanDefinitionBuilder.addPropertyReference("personDao", "personDao")
            BeanDefinition serviceDefinition = beanDefinitionBuilder.getRawBeanDefinition()
            //注册bean定义
            registry.registerBeanDefinition(serviceBeanName, serviceDefinition)
        }
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值