Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring configuration from database

Tags:

java

spring

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

like image 465
DD. Avatar asked Oct 12 '10 09:10

DD.


People also ask

How does Spring connect to database?

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.

How do you configure a DataSource in Spring?

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.

Where should Spring configuration be placed?

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 .

Which configuration in Spring data JPA provides database connection details to the application?

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.


2 Answers

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.

like image 60
Bozho Avatar answered Sep 30 '22 16:09

Bozho


@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.

like image 43
skaffman Avatar answered Sep 30 '22 14:09

skaffman