一、目的
我需要扫描指定 package 下的 service 类,并且调用工厂方法创建 bean 实例。
二、方法
spring 提供了几种定义bean的方法:
- 静态定义方式,用
<bean>
标签 - static-factory-method 方式,用
factory-method
属性 - instance-factory-method 方式,用
factory-bean
和factory-method
属性
但是这里我们在调用 factory-method 的时候需要传递一个参数,指明 service 类。所幸,spring 支持带参数的 factory-method 调用。
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)
}
}