具体代码如下:
SayHelloBean.java
package com.sias;
import com.sias.*;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
@Stateless
@Remote(SayHelloRemote.class)
@Local(SayHello.class)
@Interceptors(HelloInterceptor.class)
public class SayHelloBean implements SayHello, SayHelloRemote {
public void sayHello() {
System.out.println("Hello!");
}
public void sayName() {
System.out.println("name");
}
}
HelloInterceptor.java
package com.sias;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
public class HelloInterceptor {
@AroundInvoke
public Object log(InvocationContext ctx) throws Exception{
System.out.println("***interceptor is running***");
try{
if(ctx.getMethod().getName().equals("sayHello")){
System.out.println("sayHello()已经被调用");
}
if(ctx.getMethod().getName().equals("sayName")){
System.out.println("sayName()已经被调用");
}
return ctx.proceed();
}catch(Exception e){
throw e;
}
}
}
SayHelloRemote.java
package com.sias;
public interface SayHelloRemote {
public void sayHello();
public void sayName();
}
SayHello.java
package com.sias;
import com.sias.SayHelloRemote;
public interface SayHello extends SayHelloRemote{
}
测试代码如下:
。。。。。
InitialContext ctx=new InitialContext();
SayHelloRemote sr=(SayHelloRemote)ctx.lookup("SayHelloBean/remote");
sr.sayHello();
sr.sayName();
。。。。。
运行结果如下:
23:32:46,140 INFO [STDOUT] ***interceptor is running***
23:32:46,140 INFO [STDOUT] sayHello()已经被调用
23:32:46,140 INFO [STDOUT] Hello!
23:32:46,156 INFO [STDOUT] ***interceptor is running***
23:32:46,156 INFO [STDOUT] sayName()已经被调用
23:32:46,156 INFO [STDOUT] name