Service implementations

In case, you want to use a single implementation of your service interface, throughout your entire application, you can use the following code.

@Service(implementation = RedisSessionManager.class)
interface SessionManager {
    Session createSession();
}

@Service
class RedisSessionManager implements SessionManager {
    @Override
    public Session createSession() {
        return createMySession();
    }
}

void handleAuthentication(User user) {
    SessionManager sessionManager = Container.get(SessionManager.class);
    
    if (authorized)
        user.setSession(sessionManager.createSession());
}

You can also manually implement a service interface, using the following code.

@Service
interface DatabaseConnector {
    void connect();
}

@Service
class MySQLConnector implements DatabaseConnector {
    @Override
    public void connect() {
        requestMySQLConnection();
    }
}

void initDatabase() {
    Container.implement(DatabaseConnector.class, MySQLConnector.class);
}

void useDatabase() {
    DatabaseConnector connector = Container.get(DatabaseConnector.class);
    assert connector instanceof MySQLConnector;
}

Last updated