EJB3.0初学备注
Session Bean Example
?
?
?
@Stateless
?
1. Create a remote interface
?
4. Write test class to invoke session bean
?
?
Interceptor
?
1. Add annotation: @Interceptors({HelloInterceptor.class})
?
2. Write interceptor class
?
除了可以在外部定义拦截器之外, 还可以将Session Bean中的一个或多个方法定义为拦截器,如:
?
Test Class:
?
/** * */import java.util.*;import javax.jms.Queue;import javax.jms.QueueConnection;import javax.jms.QueueConnectionFactory;import javax.jms.QueueSender;import javax.jms.QueueSession;import javax.jms.TextMessage;import javax.naming.*;import com.ejb3.HelloWorldRemote;import com.ejb3.HelloWorldLocal;/** * @author Clay Zhong - Email: zjclay@gmail.com * @date Aug 31, 2008 */public class EJBTest {public static void main(String[] args) throws NamingException {Properties properties = new Properties();properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");properties.put(Context.PROVIDER_URL, "jnp://localhost");InitialContext ctx = new InitialContext(properties);try {QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");QueueConnection queueConnection = factory.createQueueConnection();// 建立不需要事务的并且能自动接收消息收条的会话, 在非事务Session中, 消息传递的方式有三种:// 1. Session.AUTO_ACKNOWLEDGE: 当客户机调用的receive方法成功返回,// 或当MessageListenser成功处理了消息, session将会自动接收消息的收条。// 2. Session.CLIENT_ACKNOWLEDGE: 客户机通过调用消息的acknowledge方法来接收消息。接收发生在session层。// 接收到一个被消费的消息时, 将自动接收该session已经消费的所有消息。例如:// 如果消息的消费者消费了10条消息, 然后接收15个被传递的消息, 则前面的10个消息的收据都会在这15个消息中被接收。// 3. Session.DUPS_ACKNOWLEDGE: 指示session缓慢接收消息。QueueSession queueSession = queueConnection.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);TextMessage msg = queueSession.createTextMessage("Hi, This is Clay");QueueSender sender = queueSession.createSender((Queue) ctx.lookup("queue/fortest"));sender.send(msg);queueSession.close();}catch (Exception e) {System.out.println("Lookup message driven bean failed.");}ctx.close();}}?
?
?