|
| 1 | +package io.micronaut.context.replacement |
| 2 | + |
| 3 | +import io.micronaut.context.ApplicationContext |
| 4 | +import io.micronaut.context.annotation.Context |
| 5 | +import io.micronaut.context.annotation.Replaces |
| 6 | +import io.micronaut.context.annotation.Requires |
| 7 | +import jakarta.inject.Singleton |
| 8 | +import org.junit.jupiter.api.Assertions.* |
| 9 | +import org.junit.jupiter.api.Test |
| 10 | +import java.util.concurrent.atomic.AtomicInteger |
| 11 | + |
| 12 | +interface ReplacedApi |
| 13 | + |
| 14 | +@Context |
| 15 | +@Requires(property = "spec.name", value = "ContextBeanReplacementScopeTest") |
| 16 | +open class OriginalContextApi : ReplacedApi { |
| 17 | + companion object { |
| 18 | + @JvmField |
| 19 | + val created = AtomicInteger(0) |
| 20 | + } |
| 21 | + init { |
| 22 | + created.incrementAndGet() |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +@Singleton |
| 27 | +@Replaces(OriginalContextApi::class) |
| 28 | +@Requires(property = "spec.name", value = "ContextBeanReplacementScopeTest") |
| 29 | +open class ReplacementSingletonApi : ReplacedApi { |
| 30 | + companion object { |
| 31 | + @JvmField |
| 32 | + val created = AtomicInteger(0) |
| 33 | + } |
| 34 | + init { |
| 35 | + created.incrementAndGet() |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +class ContextBeanReplacementScopeTest { |
| 40 | + |
| 41 | + @Test |
| 42 | + fun replacingContextBeanWithSingletonShouldPreventOriginalInstantiation() { |
| 43 | + // Reset counters for isolation |
| 44 | + OriginalContextApi.created.set(0) |
| 45 | + ReplacementSingletonApi.created.set(0) |
| 46 | + |
| 47 | + val ctx = ApplicationContext.run(mapOf("spec.name" to "ContextBeanReplacementScopeTest")) |
| 48 | + try { |
| 49 | + // Expected: Replacing a @Context bean with a non-@Context bean should prevent eager instantiation |
| 50 | + // Actual (bug): OriginalContextApi is still eagerly created at startup |
| 51 | + assertEquals(0, OriginalContextApi.created.get(), "Original @Context bean should not be instantiated when replaced by a non-context bean") |
| 52 | + |
| 53 | + val api = ctx.getBean(ReplacedApi::class.java) |
| 54 | + assertTrue(api is ReplacementSingletonApi, "Injected bean should be the replacement") |
| 55 | + assertEquals(1, ReplacementSingletonApi.created.get(), "Replacement bean should be constructed once on demand") |
| 56 | + assertEquals(0, OriginalContextApi.created.get(), "Original bean must not be constructed at all") |
| 57 | + } finally { |
| 58 | + ctx.close() |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments