使用限定符和仅指定所需的确切实现类有什么不同?
这个问题复制自:http ://docs.jboss.org/weld/reference/latest/en-US/html/injection.html
使用限定符和仅指定所需的确切实现类有什么不同?
这个问题复制自:http ://docs.jboss.org/weld/reference/latest/en-US/html/injection.html
一般来说,Qualifiers 形成了各方之间的脱钩层。这允许您更改一侧的实现而不更改另一侧。
However, I find it very rare to actually have more than one implementation class.
这取决于用例。虽然您可能对业务逻辑的大多数“内部”类是正确的(会有一个MailService
,而不是两个或三个),但通常有一些beantypes 有多个 implementation。
@Inject @LDAP
private AuthenticatorService
对比
@Inject @FormBased
private AuthenticatorService
已经提到了为不同的部署场景模拟/提供不同的bean 。
此外,您几乎肯定会拥有类似这样的某种逻辑,其中限定符讲述“故事的一部分”并使代码可读且结构化:
@Inject @Authenticated
private User user;
Functionally, they're the same. However, I find it very rare to actually have more than one implementation class. You'll find dependency injection to be much more useful when you're unit testing your classes. Dependency Injection allows you to easily inject a regular implementation instance during run-time. Then in your unit tests, when you're manually constructing your object to test, you can easily pass in a mock implementation.