简体   繁体   English

具有多个数据源的Spring数据控制器

[英]Spring Data Controller with Multiple Datasources

I've setup a Spring Data project with two different datasources and am trying to invoke database-specific functions from a single @Controller . 我已经用两个不同的数据源设置了一个Spring Data项目,并试图从单个@Controller调用特定于数据库的函数。 I have two separate Entity Managers, Connection Properties and Transaction Managers for each datasource. 对于每个数据源,我都有两个单独的实体管理器,连接属性和事务管理器。

Below is my current @Controller 下面是我当前的@Controller

@RequestMapping(value = "/searchDB1", produces="application/json", method = RequestMethod.GET)
    public List<Map<String, Object>> getList1() {
         List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
            "select name, id from db1.Database1"
         );
         return list;
    }
    @RequestMapping(value = "/searchDB2", produces="application/json", method = RequestMethod.GET)
    public void getList2() {
        List<Map<String, Object>> list = this.jdbcTemplate.queryForList(
            "select name, id from db2.Database2"
        );
    }

This will obviously fail as my jdbcTemplate is only wired to a single database at a time - what might be the best way for my controller to choose between databases depending on which method is called (Abstracting to Service Impl, etc.) 这显然会失败,因为我的jdbcTemplate一次仅连接到一个数据库-这可能是我的控制器根据调用哪种方法(在抽象到Service Impl等)在数据库之间进行选择的最佳方法。

There is nothing stopping you from depending on two JdbcTemplate . 没有什么可以阻止您依赖两个JdbcTemplate You have not shown the rest of the code but you could depend on two data sources and initialize the JdbcTemplate when needed as it is an utility class more than a dependable resource. 您没有显示其余的代码,但是您可以依赖于两个数据源并在需要时初始化JdbcTemplate ,因为它是实用程序类,而不是可靠的资源。

The most simple way of passing the two data sources is to make it explicit. 传递两个数据源的最简单方法是使其明确。

<bean id="myBean" class="my.Controller">
  <property name="dataSource1" ref="ds1"/>
  <property name="dataSource2" ref="ds2"/>
</bean>

Nevertheless, you can also use @Qualifier as shown in the documentation . 不过,您也可以使用@Qualifier ,如文档中所示。

@Controller
public class Controller {
    ...
    @Autowired
    @Qualifier("ds1")
    private DataSource dataSource1;

    @Autowired
    @Qualifier("ds2")
    private DataSource dataSource2;
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM