SeamFramework.orgCommunity Documentation

部分 III. Loose coupling with strong typing

The first major theme of CDI is loose coupling. We've already seen three means of achieving loose coupling:

These techniques serve to enable loose coupling of client and server. The client is no longer tightly bound to an implementation of an interface, nor is it required to manage the lifecycle of the implementation. This approach lets stateful objects interact as if they were services.

Loose coupling makes a system more dynamic. The system can respond to change in a well-defined manner. In the past, frameworks that attempted to provide the facilities listed above invariably did it by sacrificing type safety (most notably by using XML descriptors). CDI is the first technology, and certainly the first specification in the Java EE platform, that achieves this level of loose coupling in a typesafe way.

CDI provides three extra important facilities that further the goal of loose coupling:

The second major theme of CDI is strong typing. The information about the dependencies, interceptors and decorators of a bean, and the information about event consumers for an event producer, is contained in typesafe Java constructs that may be validated by the compiler.

You don't see string-based identifiers in CDI code, not because the framework is hiding them from you using clever defaulting rules—so-called "configuration by convention"—but because there are simply no strings there to begin with!

这种方法的显而易见的好处是任何IDE都可以提供自动完成,验证和重构而无需任何特殊工具。除此之外,还有第二个,不是那么明显的好处。它能够让你考虑识别对象,事件或者拦截器的时候使用注释,而不是名字,这样你将可以提升你的代码的语义水平。

CDI encourages you develop annotations that model concepts, for example,

而不是使用复合名字,像:

注释可以重用。它们能够描述系统不同部分的通用特征。它们能够帮助我们分类和理解我们的代码。它们能够以通用的方式为我们处理共同的关注点。它们能够让我们的代码具有更高的可读性,更加容易被理解。

CDI stereotypes take this idea a step further. A stereotype models a common role in your application architecture. It encapsulates various properties of the role, including scope, interceptor bindings, qualifiers, etc, into a single reusable package. (Of course, there is also the benefit of tucking some of those annotations away).

We're now ready to meet some more advanced features of CDI. Bear in mind that these features exist to make our code both easier to validate and more understandable. Most of the time you don't ever really need to use these features, but if you use them wisely, you'll come to appreciate their power.