gpt4 book ai didi

java - Maven 测试失败 - 属性 Autowiring 不起作用

转载 作者:行者123 更新时间:2023-12-01 17:41:50 27 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序,“mvn 测试”失败,因为 Autowired 无法从 application.yml 文件中读取值。

类文件:

@Configuration
public class LogConfig {

private SettingsRepository settingsRepository;

@Value("${build.version}")
private String buildVersion;

@Value("${build.name}")
private String buildName;

public LogConfig(SettingsRepository settingsRepository) {
this.settingsRepository = settingsRepository;
}

@Scheduled(fixedDelay = 5000)
public void injectDataForLogging() throws SocketException {
MDC.put("applicationToken", settingsRepository.getToken().isPresent() ? settingsRepository.getToken().get() : "NO-TOKEN");
MDC.put("macAddressList", MACAddressUtil.getMACAddresses().toString());
MDC.put("application", buildName);
MDC.put("applicationVersion", buildVersion);
}
}

application.yml:

build:
version: @project.version@
name: @project.artifactId@

pom.xml:

<artifactId>something</artifactId>
<version>2.0.0</version>

错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'logConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'build.version' in value "${build.version}"

当我运行应用程序时,一切正常:/

最佳答案

就像将 pom.xml 属性传递到 main application.yml 一样,如下所示:

        <resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>

您需要执行相同的操作才能将这些属性传递给您的测试资源:

 <build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>

关于java - Maven 测试失败 - 属性 Autowiring 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60939529/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com