如何在springboot中创建两个数据源,其中辅助数据库依赖于主数据库(最初辅助数据库未知)

c9qzyr3d  于 2023-10-15  发布在  Spring
关注(0)|答案(1)|浏览(141)

我想创建一个应用程序与两个数据库连接,其中二级数据库连接是选择的基础上,主要的。
我已经创建了两个插件,一个是@primary,另一个是我在主页加载后创建的secondary,但没有工作。

laawzig2

laawzig21#

  1. i have done something like this but not able to create second one
  2. package com.example.Configuration;
  3. import com.example.model.User;
  4. import com.example.model.UserDaoImpl;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.boot.context.properties.ConfigurationProperties;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.ComponentScan;
  10. import org.springframework.context.annotation.DependsOn;
  11. import org.springframework.jdbc.core.JdbcTemplate;
  12. import org.springframework.jdbc.datasource.DriverManagerDataSource;
  13. import org.springframework.stereotype.Component;
  14. import javax.sql.DataSource;
  15. import java.util.HashMap;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.stream.Collectors;
  19. import java.util.stream.Stream;
  20. @Component
  21. public class Registry {
  22. private static final Map<String, Object> registry = new HashMap<String, Object>();
  23. @Autowired
  24. @Qualifier("jdbcTemplate1")
  25. private JdbcTemplate jdbcTemplate1;
  26. public String getdb()
  27. {
  28. String sql1 = "select email from user1";
  29. List<User> list1 = jdbcTemplate1.query(sql1, new UserDaoImpl.UserRowMapper());
  30. return list1.get(0).getEmail();
  31. }
  32. @Bean(name = "db2")
  33. @DependsOn("db1")
  34. @ConfigurationProperties(prefix = "spring.second-db")
  35. public DataSource dataSource2() {
  36. DriverManagerDataSource dataSource = new DriverManagerDataSource();
  37. try {
  38. dataSource.setDriverClassName("com.mysql.jdbc.Driver");
  39. String jdbcurl="jdbc:mysql://localhost:3306/"+getdb();
  40. dataSource.setUrl(jdbcurl);
  41. dataSource.setUsername("root");
  42. dataSource.setPassword("hrhk");
  43. return dataSource;
  44. }
  45. catch(Exception ex)
  46. {
  47. return dataSource;
  48. }
  49. }
  50. @Bean(name = "jdbcTemplate2")
  51. @DependsOn("jdbcTemplate1")
  52. public JdbcTemplate jdbcTemplate2(@Qualifier("db2") DataSource ds) {
  53. if(ds==null)
  54. {
  55. return null;
  56. }
  57. else {
  58. return new JdbcTemplate(ds);
  59. }
  60. }
  61. }
展开查看全部

相关问题