1

I'm writing an app that talks to one database, obtains credentials for other databases, and connects to the others. It does this using a DataSource and EntityManagerFactory constructed at runtime.

If I want to use Spring Data Repositories, I think I'd need to Autowire them, and therefore they must be Spring Beans.

How can I use Spring Data if I don't have a constructed DataSource until after I run a query against the first database?

Jonas Schreiber
  • 447
  • 4
  • 13

1 Answers1

0

I believe that conditional bean creation is your answer. check here.

Also, you have to get the bean after you make sure the conditions are met. check here.

@Component
public class RuntimeBeanBuilder {

    @Autowired
    private ApplicationContext applicationContext;

    public MyObject load(String beanName, MyObject myObject) {
        ConfigurableApplicationContext configContext = (ConfigurableApplicationContext) applicationContext;
        SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();

        if (beanRegistry.containsSingleton(beanName)) {
            return beanRegistry.getSingleton(beanName);
        } else {
            beanRegistry.registerSingleton(beanName, myObject);

            return beanRegistry.getSingleton(beanName);
        }
    }
}


@Service
public MyService{

   //inject your builder and create or load beans
   @Autowired
   private RuntimeBeanBuilder builder;

   //do something
}

So, define a bean for your Spring Data Repository and set its condition to be met when the other database credentials are fetched. And then, reloading the bean using the RuntimeBeanBuilder in your service will get you the bean because now its condition is met.

Jalil.Jarjanazy
  • 839
  • 1
  • 9
  • 22