我正在努力寻找一种方法来根据请求在 DSLContext 中定义一些设置。
我想要实现的是:
我有一个 springboot API 和一个具有多个共享相同结构的模式的数据库。 根据每个请求的某些参数,我想连接到一个特定的模式,如果没有设置参数,我想连接到任何模式并失败。
为了不连接到任何架构,我编写了以下内容:
@Autowired
public DefaultConfiguration defaultConfiguration;
@PostConstruct
public void init() {
Settings currentSettings = defaultConfiguration.settings();
Settings newSettings = currentSettings.withRenderSchema(false);
defaultConfiguration.setSettings(newSettings);
}
我认为效果不错。
现在我需要一种方法来为每个请求在 DSLContext 中设置架构,因此每次我在请求期间使用 DSLContext 时,我都会自动获得到该架构的连接,而不会影响其他请求。 我的想法是拦截请求,获取参数并执行类似“DSLContext.setSchema()”的操作,但以适用于当前请求期间 DSLContext 的所有使用的方式。
我尝试定义自定义 ConnectionProvider 的请求 scopeBean,如下所示:
@Component
@RequestScope
public class ScopeConnectionProvider implements ConnectionProvider {
@Override
public Connection acquire() throws DataAccessException {
try {
Connection connection = dataSource.getConnection();
String schemaName = getSchemaFromRequestContext();
connection.setSchema(schemaName);
return connection;
} catch (SQLException e) {
throw new DataAccessException("Error getting connection from data source " + dataSource, e);
}
}
@Override
public void release(Connection connection) throws DataAccessException {
try {
connection.setSchema(null);
connection.close();
} catch (SQLException e) {
throw new DataAccessException("Error closing connection " + connection, e);
}
}
}
但是这段代码只在第一次请求时执行。后续请求不执行此代码,因此它使用第一个请求的架构。
关于如何做到这一点有什么建议吗?
谢谢
最佳答案
似乎您的请求范围 bean 被注入(inject)到单例中。
您已经在使用 @RequestScope
这很好,但是您可能会忘记在 Spring 配置类上添加 @EnableAspectJAutoProxy
。
@Configuration
@EnableAspectJAutoProxy
class Config {
}
这将使您的 bean 在单例中的代理内运行,因此会根据请求进行更改。
关于spring-boot - 每个请求的 Jooq 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65722309/