【发布时间】:2021-11-13 04:45:03
【问题描述】:
我在使用 Spring JDBC 与数据库交互的应用程序中使用 Spring Framework 版本 5.3.10。
我正在尝试将 SQL 查询隔离到 .properties 文件中。我知道有很多方法可以做到这一点,但我想知道是否有办法将@PropertySource("classpath:database/queries.properties") 引用的给定.properties 文件的所有值注入Properties(或Map)类型。
例如,如果我有一个像这样的“存储库”(或 DAO,你可以命名它)类:
@Repository
@RequiredArgsConstructor
@PropertySource("classpath:database/queries.properties")
public class ThisJdbc implements IThisJdbc {
private final Map<String, String> sqlStore; // ...values from queries.properties here
private final Properties sqlStore; // ...or here
@Override
public int[] batchInsert(final List<This> these) {
sqlStore.get("batch-insert");
...
}
...
}
我想要一种简单的方法来注入通过上述类型提供给该类的.properties 文件中的内容——或任何其他可用的键/值类型。 .properties 文件和往常一样:
find-all = select * from tb_this
find-by-col_1 = select * from tb_this where col_1 = :col_1
insert-record = insert into tb_this values (:col_1, :col_2, :col_3)
请注意,在所有这些类中注入
Environment对我来说不是一个选项;)
我一直在寻找一种使用带有固定前缀的@Value 的方法——类似于 Spring Boot 的@ConfigurationProperties,但我找不到任何相关的东西。
基本上,我想看看是否有办法使用@PropertySource 和任何类似Map 的类型来避免这种情况:
@Bean(name = "this-queries")
public PropertiesFactoryBean thisQueries() {
final var bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("database/queries.properties"));
return bean;
}
【问题讨论】: