首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用@PropertySource将.properties文件中的所有值注入属性(或映射)

使用@PropertySource将.properties文件中的所有值注入属性(或映射)
EN

Stack Overflow用户
提问于 2021-09-18 20:10:54
回答 1查看 147关注 0票数 0

我在一个使用Spring与数据库进行接口的应用程序中使用Spring Framework版本的5.3.10

我正在尝试将SQL查询隔离到.properties文件中。我知道有很多方法可以做到这一点,但我想知道是否有一种方法可以将@PropertySource("classpath:database/queries.properties")引用的给定@PropertySource("classpath:database/queries.properties")文件的所有值注入到Properties (或Map)类型中。

例如,如果我要有一个“存储库”(或DAO,您可以将其命名)类如下所示:

代码语言:javascript
复制
@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文件与往常一样:

代码语言:javascript
复制
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类型来避免这样的情况:

代码语言:javascript
复制
@Bean(name = "this-queries")
public PropertiesFactoryBean thisQueries() {
  final var bean = new PropertiesFactoryBean();
  bean.setLocation(new ClassPathResource("database/queries.properties"));
  return bean;
}
EN

回答 1

Stack Overflow用户

发布于 2021-09-20 00:06:54

@PropertySource将与@Configuration类一起使用。尽管如此,请尝试以下几点:

代码语言:javascript
复制
@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是:

代码语言:javascript
复制
queries = {key1:'query1',key2:'query2',....}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69238097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档