我有一个简单的EJB,当我通过我的独立客户端运行它时,每件事情都运行良好, 但是一旦我添加了一个拦截器,EJB中的@PostConstruct就会停止工作:
包拦截器;
public class LogInterceptor {
@PostConstruct
public void init(InvocationContext context) {
System.out.println(new Date().toString() +" Entered interceptor");
}
@PreDestroy
public void aboutToBeRemoved(InvocationContext context) {
System.out.println(new Date().toString() + " Leaving interceptor");
}
@AroundInvoke
public Object gettingToBusiness(InvocationContext context) {
String methodName = context.getMethod().getName();
System.out.println("The method name is: " +methodName);
if (methodName.equals("add")) {
}
try {
return context.proceed();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
我的测试客户:
public class Test {
public static void main(String[] args){
InitialContext ctx=getInitialContext();
ListRemote stub=null;
try {
stub = (ListRemote)ctx.lookup("ejb:/Lab12/ListEJB!interceptor.ListRemote?stateful");
} catch (NamingException e) {
System.out.println("Lookup Failed");
e.printStackTrace();
}
System.out.println("Adding data");
stub.add("Hello");
stub.add("-");
stub.add("World");
stub.add("!!!");
System.out.println("Getting data :");
for(Object o:stub.getAll()){
System.out.print(o+" ");
}
System.out.println("Removing '-' element");
stub.remove(1);
System.out.println("Getting data again:");
for(Object o:stub.getAll()){
System.out.print(o+" ");
}
stub.destroy();
}
public static InitialContext getInitialContext(){
Properties properties = new Properties();
properties.put(Context.URL_PKG_PREFIXES , "org.jboss.ejb.client.naming");
try {
return new InitialContext(properties);
} catch (NamingException e) {
System.out.println("Cannot generate InitialContext");
e.printStackTrace();
}
return null;
}
}
我的EJB:
@Stateful(name="ListEJB")
@Interceptors({LogInterceptor.class})
public class ListBean implements ListRemote{
private ArrayList<Serializable> list;
@PostConstruct
public void init(){
System.out.println("In it init ---------------------------------------------------");
list=new ArrayList<Serializable>();
}
public void add(Serializable object){
System.out.println("Currently in the list is: " +list);
System.out.println("The object is: " +object);
list.add(object);
System.out.println("Added");
}
public Serializable get(int index){
return list.get(index);
}
public void remove(int index){
list.remove(index);
}
public Object[] getAll(){
return list.toArray();
}
@Remove
public void destroy(){
list=null;
}
}
为什么它会禁用我的EJB @PostConstruct?
答案 0 :(得分:3)
在此代码中:
@PostConstruct
public void init(InvocationContext context) {
System.out.println(new Date().toString() +" Entered interceptor");
}
您正在拦截原始EJB的PostConstruct并且不允许它通过。如果要将其传递给目标EJB,则需要调用proceed:
@PostConstruct
public void init(InvocationContext context) {
System.out.println(new Date().toString() +" Entered interceptor");
context.proceed();
}
同样适用于PreDestroy。基本上它适用于所有截获的方法。请参阅EJB3 specification,第12.5节(第287页):
拦截器方法必须始终调用InvocationContext.proceed()或否 后续的拦截器方法或bean业务方法或生命周期 将调用回调方法。