We have an application which is deployed 120 times with slightly different configurations for each. We would like the configuration to be stored in the database for auditing and management purposes.
How can you instantiate Spring beans directly from the database without using XML?
Thanks
To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.
To configure your own DataSource , define a @Bean of that type in your configuration. Spring Boot reuses your DataSource anywhere one is required, including database initialization. If you need to externalize some settings, you can bind your DataSource to the environment (see “Section 25.8.
In essence the Spring configuration files (that can have any name by the way, not just the generic applicationContext. xml ) are treated as classpath resources and filed under src/main/resources .
Configuring the Datasource Bean Configure the database connection. We need to set the name of the JDBC driver class, the JDBC url, the username of database user, and the password of the database user. Create a new HikariDataSource object and return the created object.
You can't have zero XML config (unless you use JavaConfig, which doesn't make things different in your case) . You can externalize some of it to the database, and use a custom PropertyPlaceholderConfigurer
. See this article on how to achieve this.
@Bozho's suggestion is almost certainly the most practical solution, especially if the differences between the deployments is minimal and can be expressed via simple scalar properties.
The alternative is to write your own BeanFactory
implementation. This is a non-trivial exercise, and you want to be sure that it's what you need. A good starting point would be to look at the source for XmlBeanFactory
, and then write your own (DatabaseBeanFactory
, perhaps) which does something similar, but fetching the bean definitions from the database, rather than from local XML files.
It's going to be quite a lot of extra work, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With