Announcement Announcement Module
Collapse
No announcement yet.
Can Spring Autowire beans defined in a BeanFactoryPostProcessor Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Can Spring Autowire beans defined in a BeanFactoryPostProcessor

    If I add a bean definition in a BeanFactoryPostProcessor. (Something like the below) Is that bean available for autowiring? Based on my test it doesn't seem so, but maybe I'm doing something wrong. Is there a way to dynamically create a bean definition and have that be available for @Autowire injection? If I look at the @EnableJpaRepositories source it seems to create its bean definition during the @Configuration processing not during BeanFactory Post Processing.

    Code:
    public class RepoGeneratorPostProcessor implements BeanFactoryPostProcessor {
    
        public void postProcessBeanFactory(
                ConfigurableListableBeanFactory beanFactory) throws BeansException {
    
            GenericBeanDefinition jpaR = new GenericBeanDefinition();
            jpaR.setBeanClass(JpaRepositoryFactoryBean.class);
            jpaR.setAutowireCandidate(true);
            jpaR.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
            jpaR.setLazyInit(false);
            jpaR.setPropertyValues(new MutablePropertyValues().add("repositoryInterface", FirstRepository.class));
    
            RootBeanDefinition definition = new RootBeanDefinition();
            definition.setBeanClass(FirstRepository.class);
            definition.setAutowireCandidate(true);
            definition.setFactoryBeanName("&jpaR");
            definition.setFactoryMethodName("getObject");
            definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_NAME);
            definition.setLazyInit(false);
            definition.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);
    
    
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry)beanFactory;
            registry.registerBeanDefinition("jpaR", jpaR);
            registry.registerBeanDefinition("first", definition);
    
     }
    Thanks!
    Doug
Working...
X