Seymur Asadov
Seymur Asadov

Reputation: 672

Spring bind different properties files to different beans

It's my MySQL properties file

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

and Oracle properties file for datasource configuration.

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

I created two classes like this to bind properties into fields.

@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
}

When I inject these two beans to PersistenceConfiguration class same propety fields are injected.

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

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

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

enter image description here

enter image description here

How to solve this problem ?

Upvotes: 0

Views: 385

Answers (1)

Sounak Saha
Sounak Saha

Reputation: 943

This is a known problem/behavior in spring prior to spring-boot. In spring property placeholder can understand unique key. Your both properties file has same name of keys.

So the solution would be like below with fewer changes.

Change the property file like below. mysql.properties

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

Oracle properties file

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

Now change your Hibernate*Properties.java @ConfigurationProperties annotation.

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


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

No need of any change in PersistenceConfig.java file.

Upvotes: 1

Related Questions