gpt4 book ai didi

使用 Maven 测试时 Spring Boot 应用程序未读取 application.properties 文件

转载 作者:IT老高 更新时间:2023-10-28 13:47:16 27 4
gpt4 key购买 nike

更新:

我现在意识到了一些事情。我的 application.properties 文件正在正确加载,因为我通过 /env 路径验证了我的数据库属性正在加载。问题似乎是当我使用 Spring Boot maven 插件运行它时,它无法初始化我的 dataSource

mvn spring-boot:run

这会导致我的应用程序因错误而崩溃,因为其他 bean 无法初始化。奇怪的是它在 Eclipse 中运行良好。

我有一个名为 DataService 的类,它扩展了 JdbcTemplate。在我的 DataService 构造函数中,我注入(inject)了 DataSource

@Component
public class DataService extends JdbcTemplate {

@Autowired
public DataService(DataSource dataSource){
super(dataSource);
}
...more custom methods
}

我在其他 bean 中使用这个 DataService 类来执行 DB 操作。我的 DataSource 在我的 application.properties 文件中定义

spring.datasource.url: jdbc:h2:tcp://localhost/~/testdb2
spring.datasource.driverClassName: org.h2.Driver

这是我的 Application.java

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableWebMvcSecurity
@EnableAsync
@EnableScheduling
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

当我尝试使用 Maven 从 Maven 运行 jUnit 测试时,我第一次意识到这一点

mavent test

我认为这与它如何执行 jUnit 测试用例有关,但是当我只是尝试使用 maven 运行应用程序时也会发生这种情况。

我的JUnit4测试类定义如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes={Application.class})
@WebAppConfiguration
public class QuestionRepositoryIntegrationTests {
...methods
}

我使用了 Spring Boot how-to 文档 (https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html) 中的示例

当我从 Eclipse 运行这个 JUnit 类时,它工作得很好。当它从 maven 执行时,它开始按照我上面描述的那样运行。

最佳答案

尝试定义<resources>在你的 pom 的 build 部分中标记,设置资源目录的路径,其中是 application.properties :

<build>
<resources>
<resource>
<directory>resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
</build>

关于使用 Maven 测试时 Spring Boot 应用程序未读取 application.properties 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078254/

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