Spring Boot 和 Spring Session:如何控制数据源 [英] Spring Boot and Spring Session: How to control the DataSource

查看:56
本文介绍了Spring Boot 和 Spring Session:如何控制数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在同时试验 Spring Boot 和 Spring session,特别是使用 JDBC.

I'm experimenting with Spring Boot and Spring session together, specifically using JDBC.

只需在 application.properties 中添加一行:

Just adding the line in application.properties:

spring.session.store-type=jdbc

让它正常工作,这很好,因为我碰巧在那个文件中也有一些数据源属性,即

made it just work, which is nice because I happen to also have some data source properties in that file, ie

myapp.datasource.url=jdbc:mysql://localhost/etc...
myapp.datasource.driver-class-name=com.mysql.jdbc.Driver

但我实际上是将它们用于我自己的数据源和我自己的配置,就像这样:

But I'm actually using those for my own data source with my own configuration, like so:

@Configuration
@PropertySource("classpath:credentials.properties")
public class DataSourceConfig {

@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "myapp.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}
}

据我所知,Spring Session 正在创建自己的数据源,而不是使用我的.有没有办法让它改用我的?(我的真实数据源有一些额外的配置,这里没有显示 Hikari)

and as far as I can tell, Spring Session is creating its own data source instead of using mine. Is there a way I can get it to use mine instead? (my real data source has some additional configs with Hikari not shown here)

推荐答案

Spring Session 本身不创建 DataSource 而是使用应用程序上下文中存在的一个,如果它是:

Spring Session itself does not create DataSource but rather uses the one present in your application context, if it's the either:

  • 唯一的DataSource bean
  • DataSource 标记为 @Primary
  • the only DataSource bean
  • DataSource marked as @Primary

此外,如果您希望为 Spring Session 使用特定的 DataSource(例如,如果您的应用程序中有多个 DataSource),您可以通过以下方式实现:

Also if you wish to use a specific DataSource for Spring Session (for example, if you have multiple DataSources in your application) you can do that by:

  • 注释 DataSource 标记为 @SpringSessionDataSource 为 Spring Session 指定(Spring Session 2.0 以上)
  • 提供使用所需DataSourceJdbcTemplate bean 并将其命名为springSessionJdbcOperations(Spring Session 1.x)
  • annotating DataSource marked as designated for Spring Session by @SpringSessionDataSource (Spring Session 2.0 onwards)
  • providing JdbcTemplate bean that uses the desired DataSource and naming it springSessionJdbcOperations (Spring Session 1.x)

JdbcHttpSessionConfiguration.

这篇关于Spring Boot 和 Spring Session:如何控制数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆