NetBeans Platform 基於模塊化架構,提供強大的 Lookup 服務發現機制,實現模塊間鬆耦合通信。本教程通過構建一個包含 4 個模塊的 WordApp 應用,逐步演示:單模塊應用創建、基於接口與 @ServiceProvider 的服務注入、InstanceContent 與 LookupListener 實現跨模塊數據同步,掌握平台核心開發模式。
WordApp。WordEngine,代碼名基 org.demo.wordengine。Text,包 org.demo.wordengine。text)和 JButton(文本 Filter!)。private void jButton1ActionPerformed(ActionEvent evt) {
String s = text.getText();
s = s.toUpperCase();
text.setText(s);
}
運行應用,選單 Window → Text 打開窗口,輸入文本點擊按鈕驗證大寫轉換。
TextFilterTextFilter,代碼名基 org.demo.textfilter。org.demo.textfilter.TextFilter:public interface TextFilter {
String process(String s);
}
org.demo.textfilter。MyFilterMyFilter,代碼名基 org.demo.myfilter。TextFilter 模塊的依賴。package org.demo.myfilter;
import org.demo.textfilter.TextFilter;
import org.openide.util.lookup.ServiceProvider;
@ServiceProvider(service = TextFilter.class)
public class UpperCaseFilter implements TextFilter {
public String process(String s) {
return s.toUpperCase();
}
}
@ServiceProvider 編譯時自動生成 META-INF/services/org.demo.textfilter.TextFilter 文件,遵循 JDK 6 ServiceLoader 機制,Lookup 可識別並加載。
WordEngine 模塊添加對 TextFilter 模塊依賴。private void jButton1ActionPerformed(ActionEvent evt) {
String s = text.getText();
TextFilter filter = Lookup.getDefault().lookup(TextFilter.class);
if (filter != null) {
s = filter.process(s);
}
text.setText(s);
}
運行驗證功能不變,但實現了解耦:WordEngine 僅依賴接口,不知具體實現,新增過濾器只需添加新模塊並實現接口。
InstanceContent 並關聯 Lookup:private InstanceContent content;
public TextTopComponent() {
initComponents();
content = new InstanceContent();
associateLookup(new AbstractLookup(content));
}
content:content.add(s); // 發布 String 實例到自身 Lookup
History,代碼名基 com.demo.history,創建 HistoryTopComponent(editor 位置),含 JTextArea historyText。String 變化:private Lookup.Result result;
public HistoryTopComponent() {
initComponents();
result = Utilities.actionsGlobalContext().lookupResult(String.class);
result.addLookupListener(new LookupListener() {
public void resultChanged(LookupEvent e) {
historyText.setText(result.allInstances().toString());
}
});
}
Utilities.actionsGlobalContext() 返回當前活動窗口的 Lookup 代理,實現跨窗口數據感知。
啟動應用:
Lookup.Result 類型改為 Object 時的動態變化。| 機制 | 作用 |
|---|---|
| 模塊依賴 + API 導出 | 強制模塊邊界,僅通過接口通信 |
| @ServiceProvider + Lookup | 服務自動發現與注入,消費者零配置 |
| InstanceContent + LookupListener | 發布-訂閱模式實現狀態同步,無直接引用 |
NetBeans Platform 以此嚴格模塊化與 Lookup 為核心,構建高內聚、低耦合、可動態擴展的富客戶端應用基石。