Running Spring Boot Application in Dev Mode causes beans to be duplicated

121 Views Asked by At

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:

  1. Run tests using @SpringBootTest and have beans initialized from BeansInitializer
  2. Be able to run the app in the dev mode without duplicated beans?
1

There are 1 best solutions below

0
On BEST ANSWER

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