1. import javax.annotation.PreDestroy (1)
    2. import java.util.concurrent.atomic.AtomicBoolean
    3. import javax.inject.Singleton
    4. @Singleton
    5. class PreDestroyBean implements AutoCloseable {
    6. AtomicBoolean stopped = new AtomicBoolean(false)
    7. @PreDestroy (2)
    8. @Override
    9. void close() throws Exception {
    10. stopped.compareAndSet(false, true)
    11. }
    12. }
    1. import javax.annotation.PreDestroy
    2. import javax.inject.Singleton
    3. import java.util.concurrent.atomic.AtomicBoolean
    4. @Singleton
    5. class PreDestroyBean : AutoCloseable {
    6. internal var stopped = AtomicBoolean(false)
    7. @PreDestroy (2)
    8. @Throws(Exception::class)
    9. }
    10. }

    For factory beans, the preDestroy value in the annotation can be used to tell Micronaut which method to invoke.

    1. import io.micronaut.context.annotation.Bean
    2. import io.micronaut.context.annotation.Factory
    3. import javax.inject.Singleton
    4. @Factory
    5. class ConnectionFactory {
    6. @Bean(preDestroy = "stop") (1)
    7. @Singleton
    8. Connection connection() {
    9. new Connection()
    10. }
    11. }
    1. import io.micronaut.context.annotation.Bean
    2. import io.micronaut.context.annotation.Factory
    3. import javax.inject.Singleton
    4. @Factory
    5. class ConnectionFactory {
    6. fun connection(): Connection {
    7. return Connection()
    8. }
    9. }

    1. import java.util.concurrent.atomic.AtomicBoolean
    2. class Connection {
    3. AtomicBoolean stopped = new AtomicBoolean(false)
    4. void stop() { (2)
    5. stopped.compareAndSet(false, true)
    6. }
    7. }
    1. import java.util.concurrent.atomic.AtomicBoolean
    2. class Connection {
    3. internal var stopped = AtomicBoolean(false)
    4. fun stop() { (2)
    5. stopped.compareAndSet(false, true)
    6. }
    7. }