EJB Remote/Local 繫結和JNDI Lookup
從同事那裡學到一種方便的註解SessionBean的方式。程式碼我放到github去了 https://github.com/EdisonXu/Test/commit/703d49123dca9e666269771b08cc45dea6bff616 或者直接看路徑 https://github.com/EdisonXu/Test/tree/master/remote-bean-test其中test-local雖然打成了可執行jar包,但是依然無法直接通過Java -jar去執行。因為缺乏jboss相關依賴的包。我在網上沒找到dependency,所以懶得搞了。直接把本地JBoss的包配到buildPath了,直接在eclipse中執行。關鍵有兩點:1. 定義一個interface檔案:public interface RemoteTest { public static final String NAME = "Test/RemoteTest"; public static final String JNDI_NAME = "Test/RemoteTest/remote"; public String getTest(); /** * Local interface for session bean */ public static interface Local extends RemoteTest{} /** * Remote interface for session bean */ public static interface Remote extends RemoteTest{}}這樣在注入的時候直接@EJBRemoteTest.Local localRemoteTest;或者@EJBRemoteTest.Remote RemoteTest;值得注意的是,如果這裡直接用 RemoteTest 去作為型別,在載入這個包時會報錯,會提示定義的RemoteTest.NAME的值,即Test/RemoteTest不唯一。導致部署失敗。2. 方便的JNDI Lookupejb3.1支援的幾種JNDI LOOKUP:java:global/Get EJB instance by lookup global in java: Namespace. Syntax: java:global/<ear-name>/<jar-name>/<bean-name>[!<fully-qualified-interface-name>] Sample: SampleBean implements SampleBeanRemote interface SampleBeanRemote { JNDI_NAME="SampleBean";}sampleBeanInstance = (SampleBeanRemote)lookupByGlobal(SampleBeanLocal.JNDI_NAME);java:app/Get EJB instance by lookup app in java: Namespace. Note: Only effect when the expect bean is in the same ear file with the POJO calling this method. Syntax: java:app/<jar-name>/<bean-name>[!<fully-qualified-interface-name>] Sample: SampleBean implements SampleBeanLocal interface SampleBeanLocal { NAME="SampleBean";}sampleBeanInstance = (SampleBeanLocal)lookupByApp(SampleBeanLocal.NAME);java:module/Get EJB instance by lookup module in java: Namespace. Note: Only effect when the expect bean is in the same jar file with the POJO calling this method. Syntax: java:module/<bean-name>[!<fully-qualified-interface-name>] Sample: SampleBean implements SampleBeanLocal SampleBeanLocal { NAME="SampleBean";}sampleBeanInstance = (SampleBeanLocal)lookupByModule(SampleBeanLocal.NAME);其中global, app 需要提供包名,但有時候我們會在包名裡面包含版本號,這樣每次修改都要去改原始碼,很不方便。而用上面提供的REMOTE/LOCAL繫結方式,現在直接用RemoteTest rt = (RemoteTest)ctx.lookup(RemoteTest.JNDI_NAME);方便快捷。另外,還有一種方式是在jar包裡面新增ejb-jar.xml。裡面顯示的把去掉版本後的包名或別名寫到 <moduleName>中去。這樣用包名或別名替換掉原來帶版本號的包名就行了。
---------------------
作者:Edison徐
來源:CSDN
原文:https://blog.csdn.net/xeseo/article/details/9467173
版權宣告:本文為博主原創文章,轉載請附上博文連結!