首页 > 解决方案 > Spring将不同的属性文件绑定到不同的bean

问题描述

这是我的 MySQL 属性文件

mysql.properties

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 属性文件。

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

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

@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 类时,注入了相同的属性字段。

@Configuration
@EnableConfigurationProperties({ HibernateOracleProperties.class, HibernateMySQLProperties.class })
public class PersistenceConfig {

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

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

在此处输入图像描述

在此处输入图像描述

如何解决这个问题呢 ?

标签: springspring-bootspring-properties

解决方案


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

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

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

mysql.dialect=org.hibernate.dialect.MySQL57Dialect
****** all otheres same start with mysql.

Oracle 属性文件

oracle.dialect=org.hibernate.dialect.Oracle10gDialect
 ****** all otheres same start with oracle.

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

@Component("oracle_props")
@PropertySource(value = "classpath:/oracle.properties")
@ConfigurationProperties(prefix = "oracle")


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

无需对 PersistenceConfig.java 文件进行任何更改。


推荐阅读