BAE
BAE

Reputation: 8936

hk2: why bind(X.class).to(X.class)

I am learning Java, but found the following piece of code. I am confused. What is bind(X.class).to(X.class); for?

import org.glassfish.hk2.utilities.binding.AbstractBinder;
public class ApplicationBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(X.class).to(X.class);
    }
}

Thanks

Upvotes: 2

Views: 1820

Answers (2)

Waqas Ahmed
Waqas Ahmed

Reputation: 1938

By doing that you are actually binding a new contract to a service.

bind(Service.class).to(Contract.class);

OR (binding a new contract to a service in Singleton)

bind(Service.class).to(Contract.class)..in(Singleton.class);

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 209072

You're configuring how you want your services to be discovered in the DI (dependency injection) system. bind(Service).to(Contract) is basically saying that you want to provide the Service as an injectable service, and want to "advertise" it as Contract. By "advertise", I mean what you want to be able to inject it as. For instance Service can be UserRepositoryImpl, while Contract can be UserRepository (interface). With this you would only be able @Inject UserRepository as that's what you advertise. The benefit of this is all the benefits that come with programming to an interface.

Example
interface UserRepository {
    List<User> findAll();
}

class UserRepositoryImpl implements UserRepository {
    @Override
    public List<User> findAll() {
        return Arrays.asList(new User("username"));
    }
}

@Path("users")
class UserResource {
    @Inject
    private UserRepository repository;

    @GET
    public List<User> getUsers() {
        return repository.findAll();
    }
}

class JerseyApp extends ResourceConfig {
    public JerseyApp() {
        register(UserResource.class);
        register(new AbstractBinder() {
            @Override
            public void configure() {
                bind(UserRepositoryImpl.class)
                    .to(UserRepository.class);
            }
        });
    }
}

Here the UserRepository is injected into the UserResource. When the DI system injects it, it will actually be the UserRepositoryImpl instance.

Upvotes: 2

Related Questions