springboot 动态实例化数据库bean,项目启动时默认实例化配置文件里写的,之后可以通过接口传参,传入新的数据库配置信息,如url、账户密码等,实例化新对象
想自己造轮子可以看下我之前写的 https://blog.csdn.net/white_bird_shit/article/details/109496861
不想造轮子可以使用 https://gitee.com/baomidou/dynamic-datasource-spring-boot-starter
不建议把数据源做成动态的,如果一定要做,可以尝试为数据源创建一个代理,配置发生变化时改变其底层的数据源。
public class ProxyDataSource implements DataSource {
private DataSource target;
public ProxyDataSource(DataSource target) {
this.target = target;
}
public void setTarget(DataSource target) {
this.target = target;
}
@Override
public Connection getConnection() throws SQLException {
return this.target.getConnection();
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return this.target.getConnection();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return this.target.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return this.target.isWrapperFor(iface);
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return this.target.getLogWriter();
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
this.target.setLogWriter(out);
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
this.target.setLoginTimeout(seconds);
}
@Override
public int getLoginTimeout() throws SQLException {
return this.target.getLoginTimeout();
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return this.target.getParentLogger();
}
}
可以实现。你可以看看这篇帖子“SpringBoot实现通过接口动态的添加或删除数据源”。 就是通过接口参数,新增/删除数据源。并且可以使用spring的声明式事务。