简体   繁体   中英

Java Guice: If you inject the same dependency multiple times, is the same instance of that dependency injected?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM