更新:
我现在意识到了几件事。我的 application.properties
文件正在正确加载,因为我通过 /env
路径验证了我的数据库属性正在加载。问题似乎是当我使用 Spring Boot maven 插件运行它时,它无法初始化我的 dataSource
。
mvn spring-boot:run
这会导致我的应用程序因错误而崩溃,因为其他 bean 无法初始化。奇怪的是它在 Eclipse 中运行良好。
我有一个名为 DataService
的类,它扩展了 JdbcTemplate
。在我的 DataService
构造函数中,我注入了 DataSource
。
@Component
public class DataService extends JdbcTemplate {
@Autowired
public DataService(DataSource dataSource){
super(dataSource);
}
...more custom methods
}
我在其他 bean 中使用这个 DataService
类来执行数据库操作。我的 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 运行 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 执行时,它开始像我上面描述的那样运行。
原文由 John F. 发布,翻译遵循 CC BY-SA 4.0 许可协议
尝试在您的 pom 的构建部分中定义
<resources>
标记,设置资源目录的路径application.properties
: