当前位置导航:炫浪网>>网络学院>>编程开发>>JAVA教程>>J2EE

EJB 3.0 注入(会话BEAN)

    按照管理 来看看 例子 就清楚了

    这个是一个实体bean的实现

package com.ly.bean;

import javax.ejb.Remote;

@Remote
public interface Bean1 {
  public void sayBean1();
}

package com.ly.bean;
import javax.ejb.Remote;

@Remote
public interface Bean2 {
  public void sayBean2();
}


package com.ly.bean;
import javax.ejb.Remote;

@Remote
public interface Bean3 {
  public void sayBean3();
}


package com.ly.impl;

import javax.ejb.Stateless;

import com.ly.bean.Bean1;
import com.ly.bean.Bean2;
@Stateless(name="bean12")
public class Bean1Impl implements Bean1,Bean2 {

    public void sayBean1() {
      System.out.println("bean1.........");
    }
    public void sayBean2() {
     System.out.println("bean2.........");
    }

}


package com.ly.impl;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import com.ly.bean.Bean1;
import com.ly.bean.Bean2;
import com.ly.bean.Bean3;
@Stateless(name="bean3")
public class Bean2Impl implements Bean3 {
    @EJB(beanName="bean12")
    Bean1 bean1;
    Bean2 bean2;
    public void sayBean3() {
      bean1.sayBean1();
      bean2.sayBean2();
      System.out.println("bean3.........");
    }
    @EJB(mappedName="bean12/remote")
    public void setBean2(Bean2 bean2) {
        this.bean2 = bean2;
    }

}

    客户端代码:

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import com.ly.bean.Bean3;


public class Test {
  public static void main(String args[]) throws Exception{
     Properties pro = new Properties();
     pro.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
     pro.setProperty("java.naming.provider.url","localhost:1099");
     pro.setProperty("java.naming.factory.url.pkgs","org.jboss.naming");
     Context context =new InitialContext(pro);
     Bean3 bean=(Bean3) context.lookup("bean3/remote");
     bean.sayBean3();
    
  }
}

    打印结果是:

21:36:51,843 INFO [Server] JBoss (MX MicroKernel) [4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)] Started in 18s:328ms
21:36:59,921 INFO [STDOUT] bean1.........
21:36:59,937 INFO [STDOUT] bean2.........
21:36:59,937 INFO [STDOUT] bean3.........

    注入 可以在 属性上面 通过@EJB注解来标识  也可以注释在setter方法的上方

    @EJB(beanName="")指明的是 bean的指明映射名字

    而@EJB(mappedName="")指明的是  JNDI名字 比如test/remote

    注解 只能注入 本地命名服务 ,不能注入 远程服务器对象

相关内容
赞助商链接