|
| 1 | +package org.javaee7.interceptor.aroundconstruct; |
| 2 | + |
| 3 | +import javax.interceptor.AroundConstruct; |
| 4 | +import javax.interceptor.Interceptor; |
| 5 | +import javax.interceptor.InvocationContext; |
| 6 | +import java.lang.reflect.Constructor; |
| 7 | +import java.lang.reflect.Method; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author Radim Hanus |
| 11 | + */ |
| 12 | +@Interceptor |
| 13 | +@MyInterceptorBinding |
| 14 | +public class MyInterceptor { |
| 15 | + @AroundConstruct |
| 16 | + public Object onConstruct(InvocationContext context) throws Exception { |
| 17 | + // null before the InvocationContext.proceed() returns |
| 18 | + Object target = context.getTarget(); |
| 19 | + isNull(target); |
| 20 | + // null in case of AroundConstruct |
| 21 | + Method method = context.getMethod(); |
| 22 | + isNull(method); |
| 23 | + // NOT null in case of AroundConstruct |
| 24 | + Constructor ctor = context.getConstructor(); |
| 25 | + isNotNull(ctor); |
| 26 | + |
| 27 | + // perform the constructor injection |
| 28 | + Object result = context.proceed(); |
| 29 | + isNull(result); |
| 30 | + |
| 31 | + // NOT null after the InvocationContext.proceed() completes |
| 32 | + target = context.getTarget(); |
| 33 | + isNotNull(target); |
| 34 | + // a constructor should have been called |
| 35 | + GreetingBean bean = (GreetingBean) target; |
| 36 | + isBoolean(bean.isConstructed(), true); |
| 37 | + isBoolean(bean.isInitialized(), false); |
| 38 | + // constructor injection should have been done |
| 39 | + isNotNull(bean.getParam()); |
| 40 | + |
| 41 | + return null; |
| 42 | + } |
| 43 | + |
| 44 | + private static void isNull(Object o) throws Exception { |
| 45 | + if (o != null) { |
| 46 | + throw new IllegalStateException("null required"); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private static void isNotNull(Object o) throws Exception { |
| 51 | + if (o == null) { |
| 52 | + throw new IllegalStateException("not null required"); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + private static void isBoolean(Object o, Boolean value) { |
| 57 | + if (!o.equals(value)) { |
| 58 | + throw new IllegalStateException(value + " required"); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments