I have created a CDI (WELD) interceptor that works and intercept what it is supposed to intercept.
@MyInterceptorBinding
@Interceptor
@Dependent
public class MyInterceptor implements Serializable {
private int myIntegerField;
@AroundInvoke
public Object interceptMethod(InvocationContext ctx) throws Exception {
// Do some operations and side effects on myIntegerField;
try {
Object result = ctx.proceed();
return result;
} catch (Exception e) {
throw e;
}
}
public List<Class<?>> getMyIntegerField() {
return myIntegerField;
}
}
Where MyInterceptorBinding is an interceptor binding:
@Inherited
@InterceptorBinding
@Target({TYPE, METHOD, PARAMETER, FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyInterceptorBinding {}
I would like to inject my interceptor into a bean class like this:
@ApplicationScoped
public class MyBean implements Serializable {
@Inject
private MyInterceptor interceptor;
public void aMethod(){
int var = interceptor.getMyIntegerField();
// use var in some way...
}
}
but this injection brings to an error:
Unsatisfied dependencies for type MyInterceptor with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject private trials.MyBean.interceptor
How can i overcome this issue? Is a problem related to the fact that is an interceptor? Should i use the CDI portable extension facility? And, if so, how?
You can't inject interceptors because they aren't beans. What you probably can do is create a helper bean and inject that in both the interceptor and the application scoped bean. That helper bean can then contain the value, the interceptor can set it and the other bean can read it.
A warning about scopes: your MyBean
is application scoped, which means that there will be only once instance. If the interceptor is used in request scoped beans, what should the value of the interceptor value be? For this to work, the helper bean should most likely also be application scoped, and you should take care of thread safety.