EJB规范的三种Bean:会话Bean(Session Bean)、实体Bean(Entity Bean)、消息驱动
Bean(MessageDrive Bean)。
Session Bean:一个会话Bean完成一个用户功能。
无状态的会话Bean:不会保持会话状态,但是可以共享
有状态的会话Bean:可以保持会话状态,但是是暂时性的
import javax.ejb.Stateless.*;
@Stateless(name=”CalculateEJB”)//
无状态的会话bean
public class CalculateEJBBean implements CalculateEJB{
int value=0;
public String incrementValue(){
value++;
return “value incremented by 1”;
}
}
Entity Bean:代表数据库中持久性数据,创建的实体对象
import javax.persistence.*;
import java.util.Collection;
public class Employee implements java.io.Serializable{
private int empId;
private String eName;
private double sal;
public int getEmpid(){
return empId;
}
public void setEmpId(int empId){
this.empId=empId;
}
public String getEname(){
return eName;
}
public void setEname(String eName){
this.empId=eName;
}
public double getSal(){
return sal;
}
public void setSal(String sal){
this.asl=sal;
}
}
MessageDrive Bean:接收异步jms消息,要将bean指定为消息驱动的bean,需要实现
javax.jms.MesageListener接口,并且用@MessageDriven注释该bean。
import javax.ejb.MessageDriven;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.Inject;
import javax.jms.*;
import java.util.*;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerService;
@MessageDriven(
activationConfig = {
@ActivationConfigProperty(propertyName="connectionFactoryJndiName",
propertyValue="jms/TopicConnectionFactory"),
@ActivationConfigProperty(propertyName= "destinationName", propertyValue="jms/myTopic"),
@ActivationConfigProperty(propertyName= "destinationType", propertyValue="javax.jms.Topic"),
@ActivationConfigProperty(propertyName= "messageSelector", propertyValue="RECIPIENT = 'MDB'") } )
/** A simple Message-Driven Bean that listens to the configured JMS Queue or Topic and gets notified via an * invocation of it's onMessage() method when a message has been posted to the Queue or Topic.The bean
* prints the contents of the message. */
public class MessageLogger implements MessageListener, TimedObject
{
@Inject javax.ejb.MessageDrivenContext mc;
public void onMessage(Message message)
{ System.out.println("onMessage() - " + message);
try
{
String subject = message.getStringProperty("subject");
String inmessage = message.getStringProperty("message");
System.out.println("Message received\n\tDate:" + new java.util.Date() + "\n\tSubject:" + subject + "\n\tMessage:" + inmessage + "\n");
System.out.println("Creating Timer a single event timer");
TimerService ts = mc.getTimerService();
Timer timer = ts.createTimer(30000, subject);
System.out.println("Timer created by MDB at:" + new Date(System.currentTimeMillis()) +" with info:"+subject); }
catch (Throwable ex)
{ ex.printStackTrace(); }
}
public void ejbTimeout(Timer timer)
{ System.out.println("EJB 3.0:Timer with MDB");
System.out.println("ejbTimeout() called at:" + new Date(System.currentTimeMillis()));
return; }
}
注:对EJB的了解太少,需要花时间理解以及从实例中巩固,特别是三类基本的EJB
的运用。
该贴由koei123转至本版2015-2-6 4:50:46