Reputation: 133
Below is a simple web app configured as a Rest service running on glassfish4. The app itself works, can access the single resource.
Interceptor doesn't work for pong(), but magically works for helloW(). When i had activated for helloW(), i could modify and overwirte the parameter, could throw Exception, etc... But none of this works for pong(). Elsewhere i tried with stateless ejb - same result - not workding - even with ejb-jar assembly-binding deployment descriptor. Why?
Rest:
package main;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/service")
@javax.ejb.Stateless
public class Service {
@GET
@Produces("text/plain")
// @javax.interceptor.Interceptors({Intercept.class})
public String helloW(String ss){
String msg = pong("QQ");
return msg;
//return ss;
}
@javax.interceptor.Interceptors({Intercept.class})
public String pong(String m){
String temp = m;
return temp;
}
}
The interceptor itself:
package main;
@javax.interceptor.Interceptor
public class Intercept {
@javax.interceptor.AroundInvoke
Object qwe(javax.interceptor.InvocationContext ctx) throws Exception{
ctx.setParameters(new Object[]{"intercepted attribute"});
throw new Exception();
// return ctx.proceed();
}
}
And yes, i did try with beans.xml:
<interceptors><class>main.Intercept</class></interceptors>
No joy.
Upvotes: 0
Views: 875
Reputation: 1034
Disclaimer: this is a guess as I didn't found any supporting documentation about this and it might also depend on the server's/JRE implementation.
It's not working because the @GET annotated method get's invoked by using java reflection/introspection techniques. This avoids the framework to intercept that invocation as it's done directly inside the JRE.
To demonstrate this instead of invoking "pong" directly as you're doing try the following:
try {
String msg = (String) this.getClass().getDeclaredMethod("pong", String.class).invoke(this, ss);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Just replace the String msg = pong("QQ");
for that code in your sample.
You should see that the pong method is now NOT being intercepted just as happens with helloW.
The only workarround for this I can think of is what you already did: extracting the logic inside another non annotated method.
Upvotes: 1