【问题标题】:how to load property file in to spring boot project with annotations?如何使用注释将属性文件加载到 Spring Boot 项目中?
【发布时间】:2017-03-10 10:08:16
【问题描述】:

我在属性文件中编写了查询。我想在spring boot中将属性文件读入一个带有注释的类。我该如何阅读?在 Spring Boot 项目中编写查询有没有更好的方法?

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    如果您在 application.properties 文件中添加属性,您可以在 Spring Boot 类中读取它们,例如:

        @Service
        public class TwitterService {
            private final String consumerKey;
            private final String consumerKeySecret;
    
            @Autowired
            public TwitterService(@Value("${spring.social.twitter.appId}") String consumerKey, @Value("${spring.social.twitter.appSecret}") String consumerKeySecret) {
                this.consumerKey = consumerKey;
                this.consumerKeySecret = consumerKeySecret;
            } ...
    

    【讨论】:

      【解决方案2】:

      您可以通过@Value("${property.name}")注释组件中的字段

      否则,您可以使用java.util 包中的Properties 对象。

      例如,我有一个 mode 属性,其值为 dev 或 prod,我可以在我的 bean 中使用它,如下所示:

      @Value("${mode:dev}")
      private String mode;
      

      另一种方法是使用:

      Properties pro = new Properties();
      pro.load(this.getClass().getClassLoader().getResourceAsStream());
      

      【讨论】:

        【解决方案3】:

        您可以使用@PropertySource 从文件中读取属性,然后将它们传递给bean。如果您有一个名为“queries.properties”的文件,其属性如下:

        query1: select 1 from foo
        

        那么您的配置可能如下所示:

        @PropertySource("classpath:queries.properties")
        @Configuration
        public class MyConfig {
        
         @Bean
         public DbBean dbBean(@Value("${queries.query1}") String query) {
             return new DbBean(query);
         }
        

        }

        【讨论】:

          猜你喜欢
          • 2018-03-28
          • 2014-11-26
          • 2023-02-22
          • 1970-01-01
          • 2015-09-29
          • 2018-10-13
          • 1970-01-01
          • 1970-01-01
          • 2016-12-16
          相关资源
          最近更新 更多