【问题标题】:Load spring properties from library module properties file从库模块属性文件中加载弹簧属性
【发布时间】:2022-10-21 16:58:08
【问题描述】:

我有一个 spring 应用程序,我在其中创建了一个库模块,用于访问将由多个应用程序使用的 AWS Cognito。 该服务需要几个属性才能工作,这些属性在任何地方都是相同的。 所以我想在库模块中有属性文件,并在导入库时强制从那里加载属性。

我尝试在库的资源文件夹中创建一个名为 cognito-properties.yml 的文件,并创建了一个应该从中读取的配置文件。

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = CognitoService.class)
@PropertySource("classpath:/cognito-properties.yml")
public class CognitoConfiguration {
    @Value("${cognito.accessKey}")
    private String accessKey;
    @Value("${cognito.secretKey}")
    private String secretKey;

    @Bean
    public AWSCognitoIdentityProvider awsCognitoIdentityProvider() {
        return AWSCognitoIdentityProviderClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(accessKey, secretKey)))
            .withRegion(Regions.EU_NORTH_1)
            .build();
    }
}

但我无法从库中的 properties.yml 文件中加载要加载的属性。 当我将属性添加到应用程序 application.yml 文件时,它工作正常。

【问题讨论】:

    标签: java spring maven spring-properties


    【解决方案1】:

    事实证明,您不能将 @PropertySource 与 yml 文件一起使用。 它需要是一个 .properties 文件。

    【讨论】:

      【解决方案2】:

      如果你想使用 yml 文件尝试使用这个

      @PropertySource(value = "${secrets.filePath}", factory = YamlPropertySourceFactory.class)
      

      公共类 ClassToLoadProperty { }

      @Configuration
      @Component
      public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
          public YamlPropertySourceFactory() {
          }
      
          public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
              if (resource == null) {
                  return super.createPropertySource(name, resource);
              } else {
                  List<PropertySource<?>> propertySourceList = (new YamlPropertySourceLoader()).load(resource.getResource().getFilename(), resource.getResource());
                  return !propertySourceList.isEmpty() ? (PropertySource)propertySourceList.iterator().next() : super.createPropertySource(name, resource);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-23
        • 2015-04-14
        • 1970-01-01
        • 2015-11-12
        相关资源
        最近更新 更多