Question

In my JEE6-CDI-webapp, i declared a Security Interceptor, like this one:

//Secure.java
@Inherited
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@InterceptorBinding
public @interface Secure
{}

//SecurityInterceptor.java
@Secure
@Interceptor
public class SecurityInterceptor
{
    @AroundInvoke
    protected Object invoke(InvocationContext ctx) throws Exception
    {
        // do stuff
        ctx.proceed();
    }
}

And declared it inside the beans.xml:

//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
   <alternatives/>
   <decorators/>
   <interceptors>
     <class>com.profitbricks.security.SecurityInterceptor</class>
   </interceptors>
</beans>

To use it, i annotate a CDI-bean accordingly:

//CDI bean using Inteceptor
@Named @RequestScoped
@Secure
public class TestBean {
    public String doStuff() {
    }
}

Now i ask myself, do i have to annotate ALL my CDI-Beans to use this interceptor? Or is there a way to configure the beans.xml to use the interceptor for all my CDI-beans, without having to declare it for every single bean?

Was it helpful?

Solution

I don't think you can. You can however spare a bit of typing by using stereotypes:

@Named
@RequestScoped
@Secure
@Stereotype
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Secure {

}

And then annotate your beans with only @Secure

OTHER TIPS

You could try to use the small CDI Extension I wrote a few months ago:

https://github.com/struberg/InterDyn

This will allow you to dynamically apply CDI Interceptors to a bunch of classes via regexp style.

It will soon be part of Apache MyFaces CODI, I just need to find some time to cleanup the config part first ;)

These may be late, but i encountered a requirement for which i needed a global/application wide interceptor.

To enable application interceptor, annotate the interceptor as:

@Priority(Interceptor.Priority.APPLICATION)
@Interceptor
@Logging
public class MyLoggingInterceptor {}

In this case, the good news is that you dont have to declare the interceptor in the beans.xml:

Oracle javaee7 tutorial

All beans aren't useful. You can manipulate beans during bootstrapping - e.g. ultra_lite_ejbs at codi-addons (see bitbucket org) uses it. Maybe it's an inspiration for you. IMHO e.g. a community like openwebbeans.apache.org would be a better fit for your CDI related questions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top