首页 > 解决方案 > @Value:Spring 使用 application-'profile'.properties 注入自动装配依赖项时出现异常

问题描述

该应用程序有 3 个不同的 application.properties 文件

application.properties
application-aws.properties
application-local.properties

默认情况下:

spring.profiles.active=@spring.profiles.active@

在其他 2

amazon.access.key=accesskey
amazon.access.secret-key=secretkey
amazon.region=local
amazon.end-point.url=localhost:8000

在配置类中:

@Configuration
public Class AmazonConfig(){

    @Value("${amazon.access.key}")
    private String awsAccessKey;

    @Value("${amazon.access.secret-key}")
    private String awsSecretKey;

    @Value("${amazon.region}")
    private String awsRegion;

    @Value("${amazon.end-point.url}")
    private String awsDynamoDbEndPoint;
...
}

在里面pom.xml

    <build>
        <finalName>${project.name}</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

...

    <profiles>
        <profile>
            <id>local</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <spring.profile.active>local</spring.profile.active>
            </properties>
        </profile>
        <profile>
            <id>aws</id>
            <properties>
                <spring.profile.active>aws</spring.profile.active>
            </properties>
        </profile>
    </profiles>

尝试使用mvn spring-boot:run -P aws/local 我在注释机智的属性上遇到以下错误来构建应用程序@Value

INFO: The following profiles are active: @spring.profiles.active@

WARN: IllegalArgumentException - Injection of autowired dependencies failed - Could not resolve placeholder 'amazon.access.key' in value "${amazon.access.key}"

在这里的一些链接中,他们说在$之后包含一个空格,如下所示:

@Value("${amazon.access.key}")

对此:

@Value("$ {amazon.access.key}")

我的意图是能够运行“本地”配置,因此它将使用

mvn spring-boot:run -P local

当我想测试 AWS 配置时

mvn spring-boot:run -P aws

标签: javaspringmaven

解决方案


我错过了一个 Maven 插件:

<build>
 <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.1.0</version>
    </plugin>
 </plugins>
</builds>

推荐阅读