首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring将不同的属性文件绑定到不同的beans

Spring将不同的属性文件绑定到不同的beans
EN

Stack Overflow用户
提问于 2019-09-19 17:27:29
回答 1查看 78关注 0票数 0

这是我的MySQL属性文件

mysql.properties

代码语言:javascript
运行
复制
dialect=org.hibernate.dialect.MySQL57Dialect
hbm2ddl_method=validate
show_sql=true
format_sql=false
pool_name=testpool
jdbc_url=jdbc:mysql://localhost:3306/testdb
minimum_idle=2
uname=root
password=testpsw
cache_prep_stmts=true
prep_stmt_cache_size=256
prep_stmt_cache_sql_limit=2048
use_server_prep_stmts=true
maximum_pool_size=30
driver_class_name=com.mysql.jdbc.Driver

和用于数据源配置的Oracle属性文件。

代码语言:javascript
运行
复制
dialect=org.hibernate.dialect.Oracle10gDialect
hbm2ddl_method=validate
show_sql=true
format_sql=false
pool_name=testpool
jdbc_url=jdbc:oracle:thin:@localhost:1521:testdb
minimum_idle=2
uname=barn_act
password=testpsw
cache_prep_stmts=true
prep_stmt_cache_size=256
prep_stmt_cache_sql_limit=2048
use_server_prep_stmts=true
maximum_pool_size=30
driver_class_name=oracle.jdbc.OracleDriver

我创建了两个这样的类来将属性绑定到字段中。

代码语言:javascript
运行
复制
@Component("mysql_props")
@PropertySource(value = "classpath:/mysql.properties")
@ConfigurationProperties
@Getter
@Setter
public class HibernateMySQLProperties {

    private String dialect;
    //other props

}


@Component("oracle_props")
@PropertySource(value = "classpath:/oracle.properties")
@ConfigurationProperties
@Getter
@Setter
public class HibernateOracleProperties {
//same fileds as mysql
}

当我将这两个bean注入PersistenceConfiguration类时,会注入相同的属性字段。

代码语言:javascript
运行
复制
@Configuration
@EnableConfigurationProperties({ HibernateOracleProperties.class, HibernateMySQLProperties.class })
public class PersistenceConfig {

    @Autowired
    @Qualifier("oracle_props")
    private HibernateOracleProperties oracleProps;

    @Autowired
    @Qualifier("mysql_props")
    private HibernateMySQLProperties mysqlProps;
}

如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-19 19:32:21

这是spring在spring-boot之前的一个已知问题/行为。在spring中,属性占位符可以理解唯一键。您的两个属性文件具有相同的键名。

因此,解决方案将如下图所示,只需较少的更改。

如下所示更改属性文件。mysql.properties

代码语言:javascript
运行
复制
mysql.dialect=org.hibernate.dialect.MySQL57Dialect
****** all otheres same start with mysql.

Oracle属性文件

代码语言:javascript
运行
复制
oracle.dialect=org.hibernate.dialect.Oracle10gDialect
 ****** all otheres same start with oracle.

现在更改您的Hibernate*Properties.java @ConfigurationProperties注释。

代码语言:javascript
运行
复制
@Component("oracle_props")
@PropertySource(value = "classpath:/oracle.properties")
@ConfigurationProperties(prefix = "oracle")


@Component("mysql_props")
@PropertySource(value = "classpath:/mysql.properties")
@ConfigurationProperties(prefix = "mysql")

不需要在PersistenceConfig.java文件中进行任何更改。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58007844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档