0

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.

Wissam Goghrod
  • 327
  • 1
  • 5
  • 15
  • As an aside, you should [program to interfaces](https://stackoverflow.com/q/383947/2587435), meaning inject interface types, not concrete types. Use `bind(InterfaceType.class).to(ConcreteType.class)` in your Guice configuration. – Paul Samsotha Oct 02 '18 at 02:52
  • 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 Oct 02 '18 at 14:09
  • Yeah, and (unit) testing is a lot easier. You can just mock out dependencies. – Paul Samsotha Oct 03 '18 at 02:38

1 Answers1

2

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

Fernix
  • 361
  • 3
  • 10