### 上下文相關的依賴查找
應該理解為,有上下文的依賴查找。因為被 Contextualized,即被限定了一個上下文。而在這里,它的上下文就是容器(Container),就是說讓它就是在容器的范圍內進行依賴查找。但是示例代碼里面通過實現接口的方式去獲得查找能力,
然后還要提供一個容器的引用。
Contextualized dependency lookup (CDL) 是面向容器而不是注冊中心查找依賴。

項目代碼結構

類圖

~~~
public class CDLDemo {
public static void main(String... args) {
// 得先創建個容器
Container container = new DefaultContainer();
// 然后查找依賴
ManagedComponent managedComponent = new ContextualizedDependencyLookup();
managedComponent.performLookup(container);
// 調用的是實現類的 toString 方法。
System.out.println(managedComponent);
}
}
~~~
~~~
/**
* 管理依賴的容器
*/
public interface Container {
/**
*
* @param key 查找依賴所使用的 key,根據這個 key 去找到需要的依賴
* @return 返回依賴項對象實例
*/
Object getDependency(String key);
}
~~~
~~~
/**
* 容器接口的一個默認實現,寫死了依賴查找的邏輯
*/
public class DefaultContainer implements Container {
/**
*
* @param key 查找依賴所使用的 key,根據這個 key 去找到需要的依賴
* @return 如果提供的 key 的值等于 "myDependency" 則返回新的依賴項實例,
* 否則拋出異常
*/
@Override
public Object getDependency(String key) {
if ("myDependency".equals(key)) {
return new Dependency();
}
throw new RuntimeException("Unknown dependency: " + key);
}
}
~~~
~~~
/**
* 這個類作為依賴項
*/
public class Dependency {
@Override
public String toString() {
return "Hello from " + getClass();
}
}
~~~
~~~
/**
* 被管理的組件,通過向容器查找依賴
*/
public interface ManagedComponent {
void performLookup(Container container);
}
~~~
~~~
/**
* 被管理的組件的一個實現
*/
public class ContextualizedDependencyLookup implements ManagedComponent {
// 想要的依賴項
private Dependency dependency;
// 從容器中找到依賴
@Override
public void performLookup(Container container) {
this.dependency = (Dependency) container.getDependency("myDependency");
}
@Override
public String toString() {
return dependency.toString();
}
}
~~~