【发布时间】:2018-10-01 21:49:45
【问题描述】:
我有一个 java jersey 2.x 项目,使用 Guice 作为我的依赖注入框架。我有这项服务
public class AccountService {
private final AccountRepository accountRepository;
@Inject
public AccountService(InMemoryAccountRepositoryImpl inMemoryAccountRepositoryImpl) {
this.accountRepository = inMemoryAccountRepositoryImpl;
}
假设我创建了另一个同样注入InMemoryAccountRepositoryImpl 的服务类,会注入同一个实例吗?知道这一点对我来说很重要,因为这个实例的内部状态需要保持一致。
【问题讨论】:
-
顺便说一句,你应该program to interfaces,意思是注入接口类型,而不是具体类型。在 Guice 配置中使用
bind(InterfaceType.class).to(ConcreteType.class)。 -
哦,我明白了,它干净多了。如果我需要更改类的实现,而不是在注入的每个构造函数中更改它,我会在 Guice 配置中更改它一次。非常整洁,谢谢@PaulSamsotha!
-
是的,而且(单元)测试要容易得多。你可以模拟出依赖关系。
标签: java dependency-injection jersey jax-rs guice