简体   繁体   English

Spring动态bean定义自动装配

[英]Spring dynamic bean definition autowire

So first short introduction: I have a working application context, now I want to create a new bean factory that extends it with some dynamic bean definitions. 因此,首先简短地介绍一下:我有一个有效的应用程序上下文,现在我想创建一个新的bean工厂,用一些动态bean定义对其进行扩展。 So i create a new instance of DefaultListableBeanFactory passing base application context as parent. 因此,我创建了一个DefaultListableBeanFactory的新实例,将基础应用程序上下文作为父级传递。 Then I create a new bean definition: 然后创建一个新的bean定义:

BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(beanType)
                                              .setScope(BeanDefinition.SCOPE_PROTOTYPE)
                                              .setLazyInit(false)
                                              .setAbstract(false)
                                              .setDependencyCheck(AbstractBeanDefinition.DEPENDENCY_CHECK_ALL)
                                              .getBeanDefinition();

and at the end I register it with newly created bean factory 最后,我在新创建的bean工厂中注册了它

beanFactory.registerBeanDefinition(beanName, beanDef);

then some time later i would like to get new instance of that bean so I do: 然后一段时间后,我想获取该bean的新实例,所以我这样做:

Object beanInstance = beanFactory.getBean(jobType);

now i would expect that fields annotated with @Autowired are initialized.. but no. 现在我希望用@Autowired注释的字段被初始化..但是没有。 Calling beanFactory.autowireBean(beanInstance) does not help. 调用beanFactory.autowireBean(beanInstance)无济于事。

After looking up some other bean definitions in base application context i can see that my definitoin does not have any attributes and that I can add them by calling beanDef.setAttribute() but that requires me to know them in advance. 在基本应用程序上下文中查找了其他一些bean定义之后,我可以看到我的definitoin没有任何属性,可以通过调用beanDef.setAttribute()来添加它们,但这需要我提前知道它们。

Now question. 现在提问。 Is there a way to create fully initialized bean definition programmatically so it is autowired correctly? 有没有一种方法可以通过编程方式创建完全初始化的bean定义,以便正确进行自动装配?

So so i found out what i was missing: AutowiredAnnotationBeanPostProcessor it needs to be added to bean factory to fire up the @Autowired and @Value annotations. 因此,我发现了我所缺少的东西: AutowiredAnnotationBeanPostProcessor ,需要将其添加到bean工厂中以启动@Autowired@Value批注。

also for @PostConstruct and @PreDestroy you need CommonAnnotationBeanPostProcessor 对于@PostConstruct@PreDestroy也需要CommonAnnotationBeanPostProcessor

Bean factory created for application context by spring boot has total of 12 bean post processors so it is possible that some other are needed to get all features. 由Spring Boot为应用程序上下文创建的Bean工厂共有12个Bean后处理器,因此可能需要其他一些处理器才能获得所有功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM