Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Sample Analysis of using multiple data sources in SpringBoot applications

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you the use of multiple data sources in the SpringBoot application example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

Property file

First, let's define two different data source settings in the application.properties file, as follows:

Server.port=9090spring.output.ansi.enabled=ALWAYSapplication-description=@project.description@application-version=@project.version@spring.customerdatasource.url= [url1] spring.customerdatasource.username= [username1] spring.customerdatasource.password= [password1] spring.customerdatasource.driverClassName=oracle.jdbc.OracleDriverspring.billingdatasource.url= [url2] spring.billingdatasource.username= [usern ame2] spring.billingdatasource.password= [password1] spring.billingdatasource.driverClassName=oracle.jdbc.OracleDriverdatabase.sql.databasename=SELECT dbid, name FROM v$database

As I mentioned earlier, I have used the Oracle database, but you can also use other databases, as long as you change the driverClassName accordingly.

Data source configuration

To create the DataSource bean, I created a DatasourceConfig class and annotated it as a configuration, and added two data sources as two different bean:

Import javax.sql.DataSource;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.env.Environment;import org.springframework.jdbc.datasource.DriverManagerDataSource;@Configurationpublic class DatasourceConfig {Environment env; public DatasourceConfig (Environment env) {this.env = env } @ Bean (name = "customerDataSource") public DataSource customerDataSource () {DriverManagerDataSource dataSource = new DriverManagerDataSource (); dataSource.setDriverClassName (env.getProperty ("spring.customerdatasource.driverClassName")); dataSource.setUrl (env.getProperty ("spring.customerdatasource.url")); dataSource.setUsername (env.getProperty ("spring.customerdatasource.username")); dataSource.setPassword (env.getProperty ("spring.customerdatasource.password")) Return dataSource;} @ Bean (name = "billingDataSource") public DataSource billingDataSource () {DriverManagerDataSource dataSource = new DriverManagerDataSource (); dataSource.setDriverClassName (env.getProperty ("spring.billingdatasource.driverClassName")); dataSource.setUrl (env.getProperty ("spring.billingdatasource.url")); dataSource.setUsername (env.getProperty ("spring.billingdatasource.username")); dataSource.setPassword (env.getProperty ("spring.billingdatasource.password")) Return dataSource;}} data access

I used JdbcTemplate for data access. To create a DAO interface, add the IDatabaseDAO interface under the com.tech.multipledatasources.dao package, as follows:

Import com.tech.multipledatasources.domain.DatabaseInfo;public interface IDatabaseDAO {public DatabaseInfo getDatabaseInfo ();}

I made two different implementations of this interface, because even if it were a simple application, the real-life scenario would be different.

Import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.beans.factory.annotation.Value;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;import com.tech.multipledatasources.domain.DatabaseInfo;@Repositorypublic class BillingDAO implements IDatabaseDAO {private JdbcTemplate jdbcTemplate; @ Value ("${database.sql.databasename}") private String sql Public BillingDAO (@ Qualifier ("billingDataSource") DataSource datasource) {jdbcTemplate = new JdbcTemplate (datasource);} @ Override public DatabaseInfo getDatabaseInfo () {return jdbcTemplate.queryForObject (sql, new BeanPropertyRowMapper (DatabaseInfo.class));}} import javax.sql.DataSource;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.beans.factory.annotation.Value;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository Import com.tech.multipledatasources.domain.DatabaseInfo;@Repositorypublic class CustomerDAO implements IDatabaseDAO {private JdbcTemplate jdbcTemplate; @ Value ("${database.sql.databasename}") private String sql; public CustomerDAO (@ Qualifier ("customerDataSource") DataSource datasource) {jdbcTemplate = new JdbcTemplate (datasource);} @ Override public DatabaseInfo getDatabaseInfo () {return jdbcTemplate.queryForObject (sql, new BeanPropertyRowMapper (DatabaseInfo.class));}}

For the database.sql.databasename variable, add the "SELECT dbid, name FROM v$database" value to the application.properties file. Note that this SQL also applies to Oracle databases. If you plan to use a different database, you need to change this statement.

I use constructor-level dependency injection to inject data sources and use Qualifier annotations to specify the bean name.

Domain

I also use the DatabaseInfo model class to map SQL results to an object.

Import lombok.AllArgsConstructor;import lombok.Getter;import lombok.NoArgsConstructor;import lombok.Setter;import lombok.ToString;@Getter@Setter@AllArgsConstructor@NoArgsConstructor@ToStringpublic class DatabaseInfo {private long dbid; private String name;}

To keep the code clean and tidy, I used the Lombok plug-in.

Service

I added two service classes as the service layer, as shown below, annotated as services, and injected the relevant DAO classes:

Import com.tech.multipledatasources.dao.BillingDAO;import com.tech.multipledatasources.domain.DatabaseInfo;import org.springframework.stereotype.Service;@Servicepublic class BillingService {private BillingDAO billingDAO; public BillingService (BillingDAO billingDAO) {this.billingDAO = billingDAO;} public DatabaseInfo getDatabaseInfo () {return billingDAO.getDatabaseInfo ();}} import com.tech.multipledatasources.dao.CustomerDAO;import com.tech.multipledatasources.domain.DatabaseInfo;import org.springframework.stereotype.Service @ Servicepublic class CustomerService {private CustomerDAO customerDAO; public CustomerService (CustomerDAO customerDAO) {this.customerDAO = customerDAO;} public DatabaseInfo getDatabaseInfo () {return customerDAO.getDatabaseInfo ();}} exception handling

I created the CustomException class below and used central exception handling in ControllerAdvice:

Import lombok.AllArgsConstructor;import lombok.Getter;import lombok.NoArgsConstructor;import lombok.Setter;import lombok.ToString;import java.util.Date;@Getter@Setter@AllArgsConstructor@NoArgsConstructor@ToStringpublic class CustomException extends Exception {private static final long serialVersionUID = 1L; private int errStatusCode; private String errMsg; private Date errDate; private String reqDesc;} import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.context.request.WebRequest Import java.util.Date;public class ControllerExceptionHandler {@ ExceptionHandler (Exception.class) public ResponseEntity genericExceptionHandler (Exception ex, WebRequest request) {CustomException customException = new CustomException (HttpStatus.EXPECTATION_FAILED.value (), ex.getMessage (), new Date (), request.getDescription (false)); return new ResponseEntity (customException, HttpStatus.EXPECTATION_FAILED) }} Controller

I created two controllers. One for billing and one for customer requests; two service classes are injected into the controller.

Import com.tech.multipledatasources.domain.DatabaseInfo;import com.tech.multipledatasources.service.BillingService;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping ("/ billing") public class BillingController {private BillingService billingService; public BillingController (BillingService billingService) {this.billingService = billingService } @ GetMapping ("/ dsinfo") public ResponseEntity getDatasourceInfo () {return ResponseEntity.ok (billingService.getDatabaseInfo ());}} import com.tech.multipledatasources.domain.DatabaseInfo;import com.tech.multipledatasources.service.CustomerService;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController @ RestController@RequestMapping ("/ customer") public class CustomerController {private CustomerService customerService; public CustomerController (CustomerService customerService) {this.customerService = customerService;} @ GetMapping ("/ dsinfo") public ResponseEntity getDatasourceInfo () {return ResponseEntity.ok (customerService.getDatabaseInfo ());}} run the application

After running the application and request, it will return the result, which will indicate the database we just created in the connection.

The above is all the content of the article "sample Analysis of using multiple data sources in SpringBoot applications". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report