gpt4 book ai didi

java - 通过 jdbc 模板使用两个数据源

转载 作者:行者123 更新时间:2023-12-02 05:54:30 25 4
gpt4 key购买 nike

所以,我曾经做过一个 Spring Boot 项目,现在正在研究数据库。我认为最好为数据库设置两个用户:

一个可以访问用户表以进行登录/注册/信息更新,另一个可以访问其他表。

我的想法是为两个数据源创建两个单独的bean,每个数据源都有一个单独的用户,当用户想要登录时, Controller 将相应地更改 JDBCtemplate 数据源。

但我不确定这是否可行,因为 JDBCtemplate 已经定义为 spring boot 项目,并且我不知道它的范围(我假设如果它不是 session bean,则更改数据源将适用于所有用户,不仅仅是一个用户)

有人知道我应该如何解决这个问题吗?请告诉我!

最佳答案

您可以创建 2 个 JdbcTemplate bean:

// declare
@Bean("jdbc1")
public JdbcTemplate createJdbcTemplate1(@Autowired @Qualifier("datasource1") DataSource dataSource1){
return new JdbcTemplate(dataSource1);
}

@Bean("jdbc2")
public JdbcTemplate createJdbcTemplate2(@Autowired @Qualifier("datasource2") DataSource dataSource2){
return new JdbcTemplate(dataSource2);
}

并在 Autowiring 时指定bean的名称:

// use jdbcTemplate1 for login/register/information
@Autowired
@Qualifier("jdbc1")
protected JdbcTemplate jdbcTemplate1;

// use jdbcTemplate2 for other
@Autowired
@Qualifier("jdbc2")
protected JdbcTemplate jdbcTemplate2;

关于java - 通过 jdbc 模板使用两个数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51171537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com