1、依赖查找
第一种依赖查找的方式:
package app.xjtu.impl; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.ejb.EJBs; import javax.ejb.Stateless; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import app.xjtu.DependentJNDI; import app.xjtu.HelloEJBWorld; /** * 该方式的依赖注入,有以下几点疑问: * * 1、@EJB有多个时,应使用@EJBs注解 * * 2、该种方式,似乎对“HelloEJBWorld”(即依赖注入的目标),命名了一个JNDI名称 * * 3、"java:comp/env" 是服务器端的JNDI命名环境 * * */ @Stateless(mappedName="ejb/DependentJNDI") @EJBs( { @EJB(name="targetOne",beanInterface=HelloEJBWorld.class),@EJB(name="targetTwo",beanInterface=HelloEJBWorld.class) } ) public class DependentJNDIBean implements DependentJNDI { private HelloEJBWorld hello; private HelloEJBWorld hello2; @PostConstruct public void init(){ try{ Context ctx = new InitialContext(); hello = (HelloEJBWorld)ctx.lookup("java:comp/env/targetOne"); hello2 = (HelloEJBWorld)ctx.lookup("java:comp/env/targetOne"); ctx.close(); }catch(NamingException e){ throw new EJBException("初始化依赖对象时出错!",e); } } @Override public String getInfo() { return "这是第一种Dependent Lookup方式: "+hello.sayHello()+"\n hello == hello2 "+(hello == hello2); } }
第二种依赖查找的方式:
package app.xjtu.impl; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.SessionContext; import javax.ejb.Stateless; import app.xjtu.DependentJNDI; import app.xjtu.HelloEJBWorld; /** * 这是第2种dependent lookup,相比第1种: * * 1、没有异常的抛出 * * 2、需要SessionContext对象 * * 3、查找的JNDI名称简化了 * */ @Stateless(mappedName="ejb/DependentJNDITwo") @EJB(name="targetTwo",beanInterface=HelloEJBWorld.class) public class DependentJNDIBeanTwo implements DependentJNDI { @Resource SessionContext context; HelloEJBWorld hello; @PostConstruct public void init(){ hello = (HelloEJBWorld)context.lookup("targetTwo"); } @Override public String getInfo() { return "这是第2中依赖注入:"+hello.sayHello(); } }
依赖注入
这种方式,可以将Annotations放在Field或者Setter方法上。这两种的区别,暂不清楚。据说JPA的Entity Bean中2者是有区别的。(以后有时间慢慢研究)
package app.xjtu.impl; import javax.ejb.Stateless; import app.xjtu.HelloEJBWorld; @Stateless(mappedName="HelloEJBWorld") public class HelloEJBWorldBean implements HelloEJBWorld { @Override public String sayHello() { return "GlassFish EJB Client Invoked -- 通过默认的JNDI名称调用"; } }
package app.xjtu.impl; import javax.ejb.EJB; import javax.ejb.Stateless; import app.xjtu.HelloEJBWorld; import app.xjtu.Injection; @Stateless(mappedName = "ejb/Myinjection") public class InjectionBean implements Injection { @EJB private HelloEJBWorld hello; @Override public String getInfo() { return "这是EJB 注入后的输出:"+hello.sayHello(); } }这里的@EJB是按类型注入的还是按某种命名规则注入的? 原文链接:https://www.f2er.com/javaschema/287687.html