0
votes

I have a java jersey 2.x project, using Guice as my dependency injection framework. I have this service

public class AccountService {

private final AccountRepository accountRepository;

@Inject
public AccountService(InMemoryAccountRepositoryImpl inMemoryAccountRepositoryImpl) {
    this.accountRepository = inMemoryAccountRepositoryImpl;
}

Let's say that I create another service class that also injects InMemoryAccountRepositoryImpl, will the same instance be injected? It's important for me to know, because this instance has an internal state that needs to be consistent.

1
As an aside, you should program to interfaces, meaning inject interface types, not concrete types. Use bind(InterfaceType.class).to(ConcreteType.class) in your Guice configuration. - Paul Samsotha
Oh I see, it's a lot cleaner. If I need to change the implementation of the class, instead of changing it in every constructor it's injected in, I change it in the Guice config once. Pretty neat, thx @PaulSamsotha ! - Wissam Goghrod
Yeah, and (unit) testing is a lot easier. You can just mock out dependencies. - Paul Samsotha

1 Answers

2
votes

By default, Guice returns a new instance each time it supplies a value. This behaviour is configurable via scopes. Scopes allow you to reuse instances: for the lifetime of an application (@Singleton), a session (@SessionScoped), or a request (@RequestScoped). Guice includes a servlet extension that defines scopes for web apps. Custom scopes can be written for other types of applications.

for more info see the documentation