Post termination

Your services may initialize components, that must be closed/terminated. You could add a public method to clean up these resources, however you may forget to call these outside the service, before unregistering the service.

@Service
class UserManager {
    @Inject
    private DatabaseConnection connection;

    @AfterInitialized 
    private void init() {
        connection.connect();
    }
    
    @BeforeTerminate
    private void shutdown() {
        connection.close();
    }
}

void handleTermination() {
    // you may manually remove the dependency from the container
    myContainer.unset(UserManager.class);
    
    // you may manually reset the entire container
    myContainer.reset();
}

Note that both of these cases would normally open up bugs here, if you don't call explicitly a clean-up method. The dependency injector will call the termination method for your registered dependencies, as specified.

Last updated