cancel
Showing results for 
Search instead for 
Did you mean: 

Join the community at Nodes 2022, our free virtual event on November 16 - 17.

Create a repository bean at runtime

paulB
Node Clone

I faced an issue can someone help?
I need to programmatically create a spring bean for a Neo4jRepository. It manage a generic class only known at runtime.
This is my repository definition :

@Component
public interface GeneratorRepository<P extends MyType>
        extends Neo4jRepository<P, Long>, CypherdslStatementExecutor<P>

And this is how I manage to create a bean :

@Autowired
DefaultListableBeanFactory springContextBeanFactory;
RootBeanDefinition beanDefinition = new RootBeanDefinition(GeneratorRepository.class);
        beanDefinition.setTargetType(
                ResolvableType.forClassWithGenerics(GeneratorRepository.class, aMyTypeClassImpl));
        
springContextBeanFactory.registerBeanDefinition(
        aMyTypeClassImpl.getSimpleName() + GeneratorRepository.class.getSimpleName(), beanDefinition);

After that, I can get the bean name with something like :

String[] name = springContextBeanFactory.getBeanNamesForType(
                        ResolvableType.forClassWithGenerics(GeneratorRepository.class, aMyTypeClassImpl));

And I get the name for the bean that was just created. But I get BeanCreationException when doing :

springContextBeanFactory.getBean(beanNamesForType[0])

with message :
Failed to instantiate [com.my.project.generator.GeneratorRepository]: Specified class is an interface

The question is : is that possible to programmatically create a bean for an interface with generic and use it to get an Object?

Thank you for reading and for any help !

0 REPLIES 0