我在一个使用Spring与数据库进行接口的应用程序中使用Spring Framework版本的5.3.10。
我正在尝试将SQL查询隔离到.properties文件中。我知道有很多方法可以做到这一点,但我想知道是否有一种方法可以将@PropertySource("classpath:database/queries.properties")引用的给定@PropertySource("classpath:database/queries.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的@ConfigurationProperties,但是我找不到任何相关的东西。
基本上,我想看看是否有一种方法可以使用@PropertySource和任何Map-like类型来避免这样的情况:
@Bean(name = "this-queries")
public PropertiesFactoryBean thisQueries() {
final var bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("database/queries.properties"));
return bean;
}发布于 2021-09-20 00:06:54
@PropertySource将与@Configuration类一起使用。尽管如此,请尝试以下几点:
@Repository
@Configuration
@RequiredArgsConstructor
@PropertySource("classpath:database/queries.properties")
public class ThisJdbc implements IThisJdbc {
@Value("#{${queries}}")
private final Map<String, String> sqlStore; // ...values from queries.properties here
@Override
public int[] batchInsert(final List<This> these) {
sqlStore.get("batch-insert");
...
}
...
}假设您的queries.properties是:
queries = {key1:'query1',key2:'query2',....}https://stackoverflow.com/questions/69238097
复制相似问题