英文:
Running Spring Boot Application in Dev Mode causes beans to be duplicated
问题
我想在开发模式下运行我的Spring Boot应用程序:
我的主要(生产)应用程序:
fun main(args: Array<String>) {
runApplication<MyApp>(args = args, init = {
addInitializers(BeansInitializer())
})
}
开发模式下的应用程序:
import com.myApp.main as prodMain
object MyApplicationTest {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.from(::prodMain)
.with(RedisContainerDevMode::class.java)
.run(*args)
}
}
@TestConfiguration
class RedisContainerDevMode {
@Bean
@ServiceConnection("redis")
fun redis(): GenericContainer<*> =GenericContainer("redis:latest").withExposedPorts(6379)
}
除此之外,我有一个上下文初始化程序,测试时需要使用 @SpringBootTest
:
context:
initializer:
classes: com.myApp.BeansInitializer
这个初始化程序导致Bean定义被加载两次,并导致开发应用程序崩溃。
我如何同时实现以下两点:
- 使用
@SpringBootTest
运行测试,并从BeansInitializer
初始化Bean - 在开发模式下运行应用程序,避免重复加载Bean?
英文:
I want to run my Spring Boot application in the dev mode:
My main (prod app):
fun main(args: Array<String>) {
runApplication<MyApp>(args = args, init = {
addInitializers(BeansInitializer())
})
}
App in the dev mode:
import com.myApp.main as prodMain
object MyApplicationTest {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.from(::prodMain)
.with(RedisContainerDevMode::class.java)
.run(*args)
}
}
@TestConfiguration
class RedisContainerDevMode {
@Bean
@ServiceConnection("redis")
fun redis(): GenericContainer<*> =GenericContainer("redis:latest").withExposedPorts(6379)
}
Apart from this, I have a context initializer that is needed for tests using @SpringBootTest
context:
initializer:
classes: com.myApp.BeansInitializer
This initializer causes Bean definitions to be loaded twice and crashes the development app.
How I can simultaneously have:
- Run tests using
@SpringBootTest
and have beans initialized fromBeansInitializer
- Be able to run the app in the dev mode without duplicated beans?
答案1
得分: 0
我找到的解决方案是在测试中从 application.yml
中移除初始化程序,并将其移到 @SpringBootTest
注解中。
@SpringBootTest(properties = ["context.initializer.classes=com.myApp.BeansInitializer"])
这适用于集成测试和运行使用 Testcontainers 的 Spring Boot 应用程序。
英文:
The solution I found is to remove the initializer from application.yml
in tests and move it to the @SpringBootTest
annotation.
@SpringBootTest(properties = ["context.initializer.classes=com.myApp.BeansInitializer"])
This makes a perfect fit for both integration tests and running Testcontainers powered Spring Boot app
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论