Guice extensions, help to improve the developer experience of guice.
Keep the core small and scalable, and provide rich extensions arround the core.
You can use @PostConstruct and @PreDestroy on the method.
public class PostConstructTest {
@PostConstruct
public void postConstruct() {
// More code here
}
@PreDestroy
public void PreDestroy() {
// More code here
}
}You can also implements LifecycleListener.
public class ListenerTest implements LifecycleListener {
@Override
public void onStarted() {
// More code here
}
@Override
public void onStopped(Throwable error) {
// More code here
}
}@PostConstructexcute at guice object provision time,LifecycleListener.onStartedexcute when create guice injecter finished.@PostConstructwill fail fast at guice provision time.LifecycleListener.onStoppedexcuted before@PreDestroywhen object destroyed.
Be Carefull
AnyError(but notException) from the lifecycle method will stop executing more lifecycle methods directly. Which meansLifecycleListener.onStoppedand@PreDestroywill not be excuted if any destroy lifecycle method before throwsError.
User builder pattern to start up Dject.
public class DjectTest {
@Test
public void testStartUp() {
Dject.newBuilder().withModule(
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("Hello world");
}
})
.build();
}
}If you do not want to abort main thread, call awaitShutdown() after Dject build.
public class DjectTest {
@Test
public void testAwaitShutdown() {
Dject.newBuilder().withModule(
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).toInstance("Hello world");
}
})
.build().awaitShutdown();
}
}PR is very welcome.