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

Spring bind different properties files to different beans

这是我的 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

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

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

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

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

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

如何解决这个问题?

这是 spring 在 spring-boot 之前已知的 problem/behavior。在spring 属性 placeholder 可以理解unique key。您的两个属性文件具有相同的键名。

所以解决方案将像下面这样,更改较少。

更改 属性 文件,如下所示。 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 文件进行任何更改。