目录
1、不使用@Resource如何获取EJBContext/SessionContext/MessageDrivenContext的实例?
2、已通过@Resource注入的但没有定义name属性的资源如何使用JNDI访问?
1、不使用@Resource如何获取EJBContext/SessionContext/MessageDrivenContext的实例?
Context ctx = new InitialContext();
MessageDrivenContext context = (MessageDrivenContext) ctx.lookup("java:comp/EJBContext");
2、已通过@Resource注入的但没有定义name属性的资源如何使用JNDI访问?
使用
java:comp/env/fully-qalified-class-name/variable-name
或者
java:comp/env/fully-qalified-class-name/property-name
例如:
@Stateless
public class HelloBean implements com.foo.ejb.HelloRemote {
@Resource
private SessionContext sctx;
public void hello() {
try {
InitialContext ic = new InitialContext();
SessionContext sctxLookup =
(SessionContext) ic.lookup("java:comp/env/com.foo.ejb.HelloBean/sctx");
System.out.println("look up injected sctx by default name: " + sctxLookup);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
3、如何获取TimerService实例?
Context ctx = new InitialContext();
TimerService context = (TimerService) ctx.lookup("java:comp/TimerService");