1 package info.ejava.examples.ejb.interceptor.interceptors;
2
3 import javax.annotation.PostConstruct;
4 import javax.annotation.PreDestroy;
5 import javax.annotation.Resource;
6 import javax.ejb.EJBContext;
7 import javax.interceptor.AroundConstruct;
8 import javax.interceptor.AroundInvoke;
9 import javax.interceptor.AroundTimeout;
10 import javax.interceptor.Interceptor;
11 import javax.interceptor.InvocationContext;
12
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15
16 @Interceptor
17 public class LifecycleInterceptor {
18 private static final Logger logger = LoggerFactory.getLogger(LifecycleInterceptor.class);
19
20 @Resource
21 private EJBContext ejbCtx;
22
23 @AroundConstruct
24 public void ctor(InvocationContext ctx) {
25 try {
26 logger.debug("*** Contructor: {}, ejbCtx={}", ctx.getConstructor(), ejbCtx);
27 ctx.proceed();
28 } catch (Exception ex) {
29 throw new RuntimeException("error calling post construct", ex);
30 }
31 }
32
33 @PostConstruct
34 public void init(InvocationContext ctx) {
35 logger.debug("*** Lifecycle event: {}::INIT", ctx.getTarget());
36 try {
37 ctx.proceed();
38 } catch (Exception ex) {
39 throw new RuntimeException("error calling post construct", ex);
40 }
41 }
42
43 @AroundInvoke
44 public Object invoke(InvocationContext ctx) throws Exception {
45 logger.debug("*** Business Method: {}, caller={}", ctx.getMethod(), ejbCtx.getCallerPrincipal().getName());
46 Object response = ctx.proceed();
47 logger.debug("*** Response Object: {}", response);
48 return response;
49 }
50
51 @AroundTimeout
52 public Object timeout(InvocationContext ctx) throws Exception {
53 logger.debug("*** Timeout: {}", ctx.getTimer());
54 Object response = ctx.proceed();
55 return response;
56 }
57
58 @PreDestroy
59 public void destory(InvocationContext ctx) {
60 logger.debug("*** Lifecycle event: {}::DESTROY", ctx.getTarget());
61 try {
62 ctx.proceed();
63 } catch (Exception ex) {
64 throw new RuntimeException("error calling pre destroy", ex);
65 }
66 }
67 }