ITeye博客

EJB3 JNDI与依赖注入

fansofjava · 2009-02-16 00:09 · EJB3 · Markdown

JNDI是支撑EJB的核心技术,由于EJB3引入了annotation,所以无需再用XML进行配置。 考虑到不同应用服务器对JNDI的命名有所不同,所以开发时尽量考虑程序的可移植性,现将JNDI几种常见的方式列举出来,程序用到的类:

@Local
public interface IHelloWorld {
	void sayHello(String name);
}
@Stateless(name="HelloWorldBean")
public class HelloWorldBean implements IHelloWorld{
	public void sayHello(String name) {
		System.out.println("welcome to you "+name);
	}
}

name的名字与类名相同时可以省略。

@Remote
public interface IHelloWorldUser {
	public void say(String name);
}
@Stateless
@EJB(name="ejb/HelloWorldImp",beanName="HelloWorldBean",beanInterface=IHelloWorld.class)
public class HelloWorldUser implements IHelloWorldUser{
//通过EJB上下文引用
	@Resource
	private SessionContext sessionContext;
//通过EJB注解引用
	@EJB(name="ejb/HelloWorldImp")
	private IHelloWorld helloWorld0;
	public void say(String name){
		try {
			Context initialContext = new InitialContext();
//
			IHelloWorld helloWorld = (IHelloWorld) initialContext.lookup("java:comp/env/ejb/HelloWorldImp");
			helloWorld.sayHello(name);
			
			IHelloWorld helloWorld2 = (IHelloWorld) sessionContext.lookup("ejb/HelloWorldImp");
			helloWorld2.sayHello(name+"");
			
			helloWorld0.sayHello(name+"");
			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

如果在JBOSS下,可以通过

IHelloWorld helloWorld3 = (IHelloWorld) sessionContext.lookup("HelloWorldBean/local");
			helloWorld3.sayHello(name+"");

如果这样,上面的@EJB(name="ejb/HelloWorldImp"....)必须去掉,当然此引用只能在JBOSS下进行,故慎用。 这个JNDI的问题原来一直没搞清楚过,查了很多资料都没弄明白,在此要提的是,那个《EJB3入门经典》写得一塌糊涂,很混乱,越看越迷糊。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。