When The Context Closes
If you wish for a particular method to be invoked when the context is closed then you can use the javax.annotation.PreDestroy
annotation:
import javax.annotation.PreDestroy; (1)
import javax.inject.Singleton;
import java.util.concurrent.atomic.AtomicBoolean;
@Singleton
public class PreDestroyBean implements AutoCloseable {
AtomicBoolean stopped = new AtomicBoolean(false);
@PreDestroy (2)
@Override
public void close() throws Exception {
stopped.compareAndSet(false, true);
}
}
import javax.annotation.PreDestroy (1)
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Singleton
@Singleton
class PreDestroyBean implements AutoCloseable {
AtomicBoolean stopped = new AtomicBoolean(false)
@PreDestroy (2)
@Override
void close() throws Exception {
stopped.compareAndSet(false, true)
}
}
import javax.annotation.PreDestroy
import javax.inject.Singleton
import java.util.concurrent.atomic.AtomicBoolean
@Singleton
class PreDestroyBean : AutoCloseable {
internal var stopped = AtomicBoolean(false)
@PreDestroy (2)
@Throws(Exception::class)
override fun close() {
stopped.compareAndSet(false, true)
}
}
1 | The PreDestroy annotation is imported |
2 | A method is annotated with @PreDestroy and will be invoked when the context is closed. |
For factory beans, the preDestroy
value in the Bean annotation can be used to tell Micronaut which method to invoke.
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import javax.inject.Singleton;
@Factory
public class ConnectionFactory {
@Bean(preDestroy = "stop") (1)
@Singleton
public Connection connection() {
return new Connection();
}
}
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import javax.inject.Singleton
@Factory
class ConnectionFactory {
@Bean(preDestroy = "stop") (1)
@Singleton
Connection connection() {
new Connection()
}
}
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import javax.inject.Singleton
@Factory
class ConnectionFactory {
@Bean(preDestroy = "stop") (1)
@Singleton
fun connection(): Connection {
return Connection()
}
}
import java.util.concurrent.atomic.AtomicBoolean;
public class Connection {
AtomicBoolean stopped = new AtomicBoolean(false);
public void stop() { (2)
stopped.compareAndSet(false, true);
}
}
import java.util.concurrent.atomic.AtomicBoolean
class Connection {
AtomicBoolean stopped = new AtomicBoolean(false)
void stop() { (2)
stopped.compareAndSet(false, true)
}
}
import java.util.concurrent.atomic.AtomicBoolean
class Connection {
internal var stopped = AtomicBoolean(false)
fun stop() { (2)
stopped.compareAndSet(false, true)
}
}
1 | The preDestroy value is set on the annotation |
2 | The annotation value matches the method name |
| Just simply implementing the Closeable or AutoCloseable interfaces is not enough to get a bean to close with the context. One of the above methods must be used. |