JavaEE(9) - Session EJB的生命周期、事务及拦截器

时间:2021-11-08 16:17:53

1. SessionBean的生命周期

无状态Session Bean: 不存在状态-->待命状态-->被销毁状态

不存在状态-->待命状态:

1)通过构造器创建EJB实例

2)执行依赖注入

3)执行@PostConstruct回调方法

待命状态-->被销毁状态

1)执行@PreDestroy回调方法

有状态Session Bean: 不存在状态-->待命状态(<-->去活状态-->被销毁状态)-->被销毁状态

不存在状态-->待命状态

1)通过构造器创建EJB实例

2)执行依赖注入

3)执行@PostConstruct回调方法

待命状态-->去活状态

1)执行@PrePassive回调方法

去活状态-->待命状态

1)执行@PostActivate回调方法

待命状态-->被销毁状态

1)客户端调用@Remove方法

2)执行@PreDestroy回调方法

#1. 开发EJB(Net Beans创建EJB Module, 项目名称:Lifecycle)

ShopService.java

package org.crazyit.service;

import javax.ejb.*;
import java.util.*; @Remote
public interface ShopService {
void addItem(String item);
Map<String, Integer> showDetail();
void remove();
}

ShopServiceBean.java

package org.crazyit.service;

import java.util.*;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.*; @Stateful(mappedName = "ShopService")
public class ShopServiceBean implements ShopService { private Map<String, Integer> buyInfo = new HashMap<String, Integer>(); public void addItem(String item) {
//该物品已经购买过
if (buyInfo.containsKey(item)) {
buyInfo.put(item, buyInfo.get(item) + 1);
} else {
buyInfo.put(item, 1);
}
} public Map<String, Integer> showDetail() {
return buyInfo;
} @Remove
public void remove() {
System.out.println("执行@Remove修饰的方法!");
} //下面定义了5个简单的生命周期方法
@Init
public void init() {
System.out.println("执行@Init修饰的方法!");
} @PostConstruct
public void postConstruct() {
System.out.println("执行@PostConstruct修饰的方法!");
} @PrePassivate
public void prePassivate() {
System.out.println("执行@PrePassivate修饰的方法!");
} @PostActivate
public void postActivate() {
System.out.println("执行@PostActivate修饰的方法!");
} @PreDestroy
public void preDestroy() {
System.out.println("执行@PreDestroy修饰的方法!");
}
}

#2. 客户端调用EJB (参见8.5)

2. 容器管理事务

#1. EJB开发(Net Beans创建EJB Module, 项目名称:CMT)

Cmt.java

package org.crazyit.service;

import javax.ejb.Remote;

@Remote
public interface Cmt {
void insert();
}

CmtBean.java

package org.crazyit.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource; @Stateless(mappedName = "cmt")
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class CmtBean implements Cmt { private DataSource ds = null; @Resource
private SessionContext sessCtx; public CmtBean() throws NamingException {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("javaee");
} public void insert() {
try {
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate("insert into user_table values(null, '新用户' , 'bbb')");
System.out.println(result);
//下面这条语句将引起失败
stmt.executeUpdate("insert into user_table values(1, 'aaa' , 'bbb')");
stmt.close();
conn.close();
}
catch (SQLException ex) {
ex.printStackTrace();
sessCtx.setRollbackOnly();
}
}
}

#2. 客户端调用EJB (Net Beans创建Java Project: CmtTest)

Cmt.java

package org.crazyit.service;

public interface Cmt {
void insert();
}

EjbClient.java

package lee;

import javax.rmi.*;
import javax.naming.*;
import java.util.Properties; import org.crazyit.service.*; public class EjbClient { public void test() throws NamingException {
//获取WebLogic中JNDI服务的Context
Context ctx = getInitialContext();
Cmt cmt = (Cmt) ctx.lookup("Cmt#org.crazyit.service.Cmt");
cmt.insert();
} //工具方法,用来获取WebLogic中JNDI服务的Context
private Context getInitialContext() {
// 参见(4)
} public static void main(String[] args) throws Exception {
EjbClient client = new EjbClient();
client.test();
}
}

3. Bean管理事务

#1. EJB开发(Net Beans创建EJB Module, 项目名称:BMT)

Bmt.java

package org.crazyit.service;

import javax.ejb.Remote;

@Remote
public interface Bmt {
void insert() throws Exception;
}

BmtBean.java

package org.crazyit.service;

import java.util.*;
import javax.ejb.*;
import javax.annotation.*;
import javax.naming.*; import java.sql.*;
import javax.sql.*;
import javax.transaction.*; @Stateless(mappedName = "bmt")
@TransactionManagement(TransactionManagementType.BEAN)
public class BmtBean implements Bmt { private DataSource ds = null; @Resource
private UserTransaction trans; public BmtBean() throws NamingException {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("javaee");
} public void insert() throws Exception {
try {
//开始事务
trans.begin();
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate("insert into user_table values(null, 'BMT插入的记录' , 'bbb')");
System.out.println(result);
//下面这条语句将引起失败
stmt.executeUpdate("insert into user_table values(1, 'aaa' , 'bbb')");
//提交事务
trans.commit();
stmt.close();
conn.close();
}
catch (SQLException ex) {
ex.printStackTrace();
//回滚事务
trans.rollback();
}
}
}

#2. 客户端调用EJB (Net Beans创建Java Project: BmtTest)

Bmt.java

package org.crazyit.service;

public interface Bmt {
void insert() throws Exception;
}

EjbClient.java

package lee;

import javax.rmi.*;
import javax.naming.*;
import java.util.Properties; import org.crazyit.service.*; public class EjbClient { public void test() throws Exception {
//获取WebLogic中JNDI服务的Context
Context ctx = getInitialContext();
Bmt bmt = (Bmt) ctx.lookup("Bmt#org.crazyit.service.Bmt");
bmt.insert();
} //工具方法,用来获取WebLogic中JNDI服务的Context
private Context getInitialContext() {
// 参见(4)
} public static void main(String[] args) throws Exception {
EjbClient client = new EjbClient();
client.test();
}
}

4. 拦截器

#1. EJB开发(Net Beans创建EJB Module, 项目名称:Interceptor)

MyInterceptor.java

package org.crazyit.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext; public class MyInterceptor { @AroundInvoke
public Object log(InvocationContext ctx) throws Exception {
System.out.println("------拦截器开始运行------");
//让目标方法执行
Object rvt = ctx.proceed();
if (rvt != null) {
rvt = "拦截器改变了返回值:" + rvt;
}
System.out.println("------拦截器执行结束------");
return rvt;
}
}

HelloCrazyit.java

package org.crazyit.service;

import javax.ejb.*;

@Remote
public interface HelloCrazyit{
String hello(String name);
void crazyit();
void exclude();
}

HelloCrazyitBean.java

package org.crazyit.service;

import java.util.*;
import javax.ejb.*;
import javax.annotation.*;
import javax.interceptor.*;
import org.crazyit.interceptor.*; @Stateless(mappedName = "HelloCrazyit")
@Interceptors(MyInterceptor.class)
public class HelloCrazyitBean implements HelloCrazyit { public String hello(String name) {
System.out.println(name + ", 您好!现在时间是:" + new java.util.Date());
return "crazyit.org";
} public void crazyit() {
System.out.println("疯狂Java联盟!");
System.out.println("最受欢迎的Java论坛!");
} @ExcludeClassInterceptors
public void exclude() {
System.out.println("被排除在拦截器机制之外的方法!");
}
}

#2. 客户端调用EJB (Net Beans创建Java Project: InterceptorTest)

HelloCrazyit.java

package org.crazyit.service;

public interface HelloCrazyit {
String hello(String name);
void crazyit();
void exclude();
}

EjbClient.java

package lee;

import javax.rmi.*;
import javax.naming.*;
import java.util.Properties; import org.crazyit.service.*; public class EjbClient { public void test()
throws Exception {
//获取WebLogic中JNDI服务的Context
Context ctx = getInitialContext();
HelloCrazyit bmt = (HelloCrazyit) ctx.lookup("HelloCrazyit#org.crazyit.service.HelloCrazyit");
System.out.println(bmt.hello("yeeku"));
bmt.crazyit();
bmt.exclude();
} //工具方法,用来获取WebLogic中JNDI服务的Context private Context getInitialContext() {
// 参见(4)
} public static void main(String[] args) throws Exception {
EjbClient client = new EjbClient();
client.test();
}
}