如何在spring-boot项目中访问依赖资源属性

问题描述

依赖变量面临的问题。

我有一些核心依赖项目。他们有自己的属性。现在,当我在项目中使用这些依赖项时,我不想在application.properties文件中再次定义这些属性。同样,如果我在application.properties中定义了相同的变量,它将覆盖依赖项属性

例如。

DependencyProjectA
    -src/main/java
        -com.myApp.accessor
            ResourceAccessor.java
             {
               @Value("${projectA.value}")
                private String projectValue;
             }
    -src/test/resources
        -projectA.properties
          projectA.value: test123

ProjectB (dependent on ProjectA)
    -src/main/java
        -xyz.java
         {
           @Value("${projectB.value}")
           private String projectValue;

         }
    -src/test/resources
         -application.properties
           projectB.value: test123

    -pom.xml
     <dependency>
      DependencyProjectA
     </dependency>

现在,当我使用命令 java -jar target / projectB.jar @H_502_12@运行projectB jar时 我面临以下问题:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'projectA.value' in value "${projectA.value}"
        at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236) ~[spring-core-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]

我们如何使用依赖项属性文件(projectA.properties)而不是在projectB属性文件(application.properties)中进行定义来解决依赖项jar变量。

解决方法

如果我理解正确,您的属性文件位于 src/main/resources 但不在 src/test/resources 中,否则测试属性文件不会打包在最终 jar 文件中。 对于 Spring Boot 2.4.0 或更新版本,您可以使用属性 spring.config.import

示例:

spring.config.import=classpath:projectA.properties

对于较旧的 Spring Boot 版本,我使用应用程序参数 spring.config.additional-location 来运行应用程序:

spring.config.additional-location=classpath:projectA.properties

无论如何你都可以设置PropertySourcesPlaceholderConfigurer

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        Resource[] resources = new ClassPathResource[]{new ClassPathResource("projectA.properties")};
        pspc.setLocations(resources);
        pspc.setIgnoreUnresolvablePlaceholders(true);
        return pspc;
    }

还有一些额外的属性可以自定义加载自定义属性文件的文件夹。 请检查:https://docs.spring.io/spring-boot/docs/2.1.9.RELEASE/reference/html/boot-features-external-config.html