Posted on 2009-03-24 10:26
小強摩羯座 閱讀(426)
評論(0) 編輯 收藏 所屬分類:
Java
jndi全局注冊表和enc的基本概念 |
通俗的將jndi就是對ejb容器中所有的資源和組件進行管理的花名冊,通過該服務,可以很方便的找到希望使用的資源。當組件被部署到服務器上后,該組件就會被自動注冊到花名冊上,以便用戶使用,如果組件被卸載,花名冊上的記錄就會自動消失。
jndi中注冊的所有的資源和組件可以被服務器內外的各種程序請求或者訪問,是一種全局性的資源!但是ejb中不同的組件通過全局性的jndi服務器形成依賴關系,則會給系統造成不穩定的因素!因此就引入了enc(ejb組件的企業名稱上下文)的概念!通過她來實現不同組件之間的引用關系!!!!
在上一篇文章中寫到了通過標注的方式實現方向依賴注入!還以上篇為例:
有接口:HelloWordRemote HelloWordLocal ICal(Remote)
而HelloWordBean實現了分別實現了他們
另外又有了個遠程接口:
@Remote
public Interface MyService{
public String helloWord();
public int add(int a,int b);
}
一個類想實現這個接口并且在這個類中引用了...如下:
@Stateless
public class FacedServcie implements MyService{
private HelloWordLocal myserv1;
private ICal ical;
.....
....
}
可以通過配置文件實現反向依賴注入:
<ejb-jar
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0">
<enterprise-beans>
<session>
<ejb-name>FacedServcie</ejb-name>
<ejb-ref>
<ejb-ref-name>abc1</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote>com.ICal</remote>
<mapped-name>HelloWordBean1/remote</mapped-name>
<injection-target>
<injection-target-class>
xiaoxiao.FacedService
</injection-target-class>
<injection-target-name>
ical
</injection-target-name>
</injection-target>
</ejb-ref>
.........(對于另一個組件的配置)
</session>
</enterprise-beans>
</ejb-jar>
還可以通過檢索的方式來實現:
@Stateless
public class FacedServcie implements MyService{
private HelloWordLocal myserv1;
private ICal ical;
public String helloWord(){
try{
InitialContext ctx=new InitalContext();
ical=(ICal)ctx.lookup("java:comp/env/abc1");
//其中java:comp/env是組件局部enc所有記錄的根路徑而abc1是在配置文件中注冊的名字!
}catch(NamingException e){}
if(ical!=null){
return ical.helloWord();
}else{
return "error!";
}
}
....
}
配置文件如下:
<ejb-jar
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0">
<enterprise-beans>
<session>
<ejb-name>FacedServcie</ejb-name>
<ejb-ref>
<ejb-ref-name>abc1</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote>com.ICal</remote>
<mapped-name>HelloWordBean1/remote</mapped-name>
</ejb-ref>
.........(對于另一個組件的配置)
</session>
</enterprise-beans>
</ejb-jar>
本人建議使用第一種反向依賴注入的方式!
還有其他的一些注入:如持久化單元注入,資源型注入 數據源類型的注入。。。
|
|
|
|