Set @Bean Datasource at runtime in Java Spring Boot

Asked

Viewed 133 times

0

In the Java with Spring Boot framework the @Bean are normally automatically set, including the DataSource which is the main issue, but also has as settar the @Bean manually by code in the case of DataSource, making a method with the notation @Bean that returns a DataSource then just return the DataSource any way you want it.

But there’s a problem, this @Bean is set in the project startup and I need to get the project started with this @Bean "empty" and that it is set at runtime, but I have searched a lot and have not found a way to set a @Bean at runtime, I have already managed to make the project give startup with the @Bean "empty" I just can’t set the @Bean at runtime.

Someone can give me a light?

  • Bruno, isn’t multitenancy what you want? You can maintain the connection between two or more banks and define which one will be used based on the request you receive for example. Take a look at this example: https://bytefish.de/blog/spring_boot_multitenancy/

  • @hebertrfreitas could explain me better, because the idea is that it can maintain the connection with several banks, dynamically, without pre-configuration of the banks

  • Bruno, but at what point will you know the database settings, such as IP or dns, port, user, password, etc ? You have a limited datasource set that you need to consult ?

  • @hebertrfreitas these settings would come from an endpoint that, when executed, "settaria" these database configuration data that will be used.

  • Bruno, the idea of multitenancy is for you to dynamically switch between a limited number of datasources, where you may already know the access settings. In your case it seems to me that the application "can connect anywhere". In that sense, your architecture really needs to be this way ? If yes, provide the part of the code where you are creating Datasource programmatically.

  • @hebertrfreitas my idea is yes connect in any place q I command, the number of datasources can be 1 or 10 (will not be mto but I do not know how many will be and I do not have the properties of datasources currently), the code q I create Datasource programmatically is summarized in a class annotated with "@ Configuration" and which has a method called "datasource()" that returns exactly this: "Datasourcebuilder.create(). username(...). password(...). url(...). build();"

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.