spring - 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;
}
如何解决这个问题呢 ?
解决方案
这是 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 文件进行任何更改。
推荐阅读
- html - 仅模糊背景图像而不是前面的文本
- decentralized-identity - 尝试使用 ion 方法注册时收到错误的请求响应
- json - Console.log() 不工作,但 Alert() 功能工作
- c# - 对于带有 docker-compose 的 ASP.NET 应用程序,我应该使用什么数据库主机名?
- php - 如何使用 PHP 将所有类从 html 获取到数组
- java - 如何在没有逗号的情况下显示数字java
- html - CSS 和 HTML 在图像上放置偏移内容以产生交错效果
- android - 在视图寻呼机制作的图像中放置按钮?
- python - scrapy crawlspider“拒绝”无效设置
- database - 尝试从 Web 应用程序访问时出现 REST API CORS 错误