Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 334
BAE Avatar asked Feb 12 '26 06:02

BAE


1 Answers

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.

like image 160
Paul Samsotha Avatar answered Feb 15 '26 13:02

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!