EJB3入门

还是拿一个EJB3的例子来说吧。

先定义一个远程接口。
package com.bms;

import javax.ejb.Remote;

@Remote
public interface FacadeBeanRemote {
	
	public String question();

}


用无状态会话Bean实现这个接口。
package com.bms;

import javax.ejb.Stateless;

/**
 * Session Bean implementation class Facade
 */
@Stateless(mappedName = "FacadeBean")
public class FacadeBean implements FacadeBeanRemote {

    /**
     * Default constructor. 
     */
    public FacadeBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public String question() {
		return "who am i";
	}

}


ejb-jar.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:ejb="http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0">
  <display-name>bpm3-ejb </display-name>
</ejb-jar>


weblogic-ejb-jar.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-ejb-jar xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-ejb-jar" 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 http://xmlns.oracle.com/weblogic/weblogic-ejb-jar http://xmlns.oracle.com/weblogic/weblogic-ejb-jar/1.2/weblogic-ejb-jar.xsd">
    <!--weblogic-version:10.3.6-->
    <wls:weblogic-enterprise-bean>
        <wls:ejb-name>FacadeBean</wls:ejb-name>
        <wls:stateless-session-descriptor></wls:stateless-session-descriptor>
        <wls:jndi-name>FacadeBean</wls:jndi-name>
    </wls:weblogic-enterprise-bean>
</wls:weblogic-ejb-jar>


部署EJB项目到weblogic server上。

客户端调用代码如下:
package com.bms;

import java.util.Properties;

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

public class Ejb3InvocationTest {

	public static void main(String[] args) {
		Properties p = new Properties();
		p.put(Context.INITIAL_CONTEXT_FACTORY,
				"weblogic.jndi.WLInitialContextFactory");
		p.put(Context.PROVIDER_URL, "t3://localhost:7001");
		p.put(Context.SECURITY_PRINCIPAL, "weblogic");
		p.put(Context.SECURITY_CREDENTIALS, "welcome1");

		InitialContext ctx;
		try {
			ctx = new InitialContext(p);
			FacadeBeanRemote remote = (FacadeBeanRemote) ctx
					.lookup("FacadeBean#com.bms.FacadeBeanRemote");
			System.out.println(remote.question());

		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}

	}

}

JNDI的查找名为MappedName#远程接口的类名,即FacadeBean#com.bms.FacadeBeanRemote。

需要注意的是为了让客户端代码可以正常调用,在EJB项目的Libraries里面要拿掉WebLogic System Libraries,同时在项目路径下加入wlfullclient.jar包。

执行客户端调用代码,打印出“who am i”。

Done!!!!!!!!!!!!!

猜你喜欢

转载自cutesunshineriver.iteye.com/blog/1958931