Friday, September 24, 2010

Interceptor Advisor Pattern

Your standard CDI/EJB Interceptor example uses a logger as an around advice. Generally this gives you an interceptor that looks like so:

@Log
public class LoggingInterceptor {

    private java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger("theLogger");

    @AroundInvoke
    public Object intercept(InvocationContext context) throws Exception {
        logger.info("" + context.getMethod().getName());
        return context.proceed();
    }
}

As of the Interceptors 1.1 spec, you can bind that to a bean via creating our own javax.interceptor.InterceptorBinding annotation. In our example, we've created one called @Log:

@InterceptorBinding
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}

Now we just apply that to the bean as follows.

@Log
public class FooBean {

    public void somethingCommon(){
        //...
    }

    public void somethingImportant() {
        //...
    }

    public void somethingNoteworthy() {
        //...
    }
}

Great! Now we are done. Every time that bean is invoked, the LoggerInterceptor will issue a log message on info level. Aren't interceptors wonderful! End of story, right? Not quite.

Fundamentally, our example is still very contrived. Who wants to log everything on the same level?

Here is a little pattern that you can use to better advise your LoggerInterceptor around advice. First, we create a couple new annotations for log levels: @Fine and @Info

@Target(value = {ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Fine {
}

@Target(value = {ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Info {
}

Then we apply those to the bean...

@Log
public class FooBean {

    public void somethingCommon(){
        //...
    }

    @Info
    public void somethingImportant() {
        //...
    }

    @Fine
    public void somethingNoteworthy() {
        //...
    }
}

Now we alter our LoggerInterceptor to check for our new annotations and alter its behavior.

@Log
public class LoggingInterceptor {

    private java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger("theLogger");

    @AroundInvoke
    public Object intercept(InvocationContext context) throws Exception {
        final Method method = context.getMethod();
        if (method.isAnnotationPresent(Info.class)) {
            return info(context);
        } else if (method.isAnnotationPresent(Fine.class)) {
            return fine(context);
        } else {
            return finest(context);
        }
    }

    public Object info(InvocationContext context) throws Exception {
        logger.info("" + context.getMethod().getName());
        return context.proceed();
    }

    public Object fine(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }

    public Object finest(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }
}

Done! Now we have a pattern to advise our interceptor!

This will totally work today. But this pattern is so simple and elegant what if we could support it right inside the container? Imagine how cool it would be if we could just do this in our interceptor and the container would just figure it out.

@Log
public class LoggingInterceptor {

    private java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger("theLogger");

    @Info
    public Object info(InvocationContext context) throws Exception {
        logger.info("" + context.getMethod().getName());
        return context.proceed();
    }

    @Fine
    public Object fine(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }

    @AroundInvoke
    public Object finest(InvocationContext context) throws Exception {
        logger.finest("" + context.getMethod().getName());
        return context.proceed();
    }
}

Definitely something I plan to propose for the next round of specifications....

As always, comments welcome.

25 comments:

Unknown said...

20170619 junda
oakley sunglasses sale
cheap jerseys wholesale
burberry outlet sale
cheap ray ban sunglasses
adidas uk store
michael kors outlet clearance
cheap nba jerseys
true religion outlet
ray ban sunglasses
nike air max 90

Unknown said...

20170619 junda
rolex watches,rolex watches,swiss watches,watches for men,watches for women,omega watches,replica watches,rolex watches for sale,rolex replica,rolex watch,cartier watches,rolex submariner,fake rolex,rolex replica watches,replica rolex
ray ban sunglasses
ferragamo outlet
ray ban wayfarer
true religion jeans sale
fitflops
christian louboutin sale
ralph lauren outlet
jordan 4
cheap nfl jerseys

Habib Malik said...

Sarkari Naukri
OBC Bank Recruitment 2018

Danish Ahmed said...

Thanks for sharing this article, now you can check your cut off marks by following below given links

rajasthan post office gds result 2017

north eastern post office gds result 2017

karnataka post office gds result 2017

punjab post office gds result 2017

uttarakhand post office gds result 2017

Danish Ahmed said...

Thanks for sharing this article, now you can check your Time table & Date sheet 2017 by following below given links

ap ssc time table 2017

assam hslc date sheet 2017

bihar board 10th date sheet 2017

cbse board 10th date sheet 2017

ch board 10th date sheet 2017


luu quoc trung said...

Thank you both for sharing Holy Mass with us each day FNAF Sister Location Juegos Friv Friv 2018 to make yourselves available Friv Twizl Jeux De Twizl Juegos De FNAF Sister Location when we were called out late at night and any other time and for your support and encouragement in every respect. Juegos Friv 2021 Juegos Twizl Juegos Yepi 2017 Juegos De Twizl

Danish Ahmed said...

Thanks for sharing this article, now you can also check your Admit card & Recuritment 2017 by following below given links...

police si admit card 2017

gpsc medical officer admit card 2017

tamilnadu teacher recuritment 2017

bihar police constable recuritment 2017

gujarat high court recruitment 2017

Danish Ahmed said...

Thanks for sharing this article, now you can also check your Admit Card 2017 by following below given links...

gsssc food safety officer admit card 2017

hssc pgt admit card 2017

Habib Malik said...

Kalyani University Routine 2018
Tripura Board Madhyamim Date Sheet 2018
Tripura Board HS Date Sheet 2018
Telangana SSC Date Sheet 2018
Telanagana Intermediate Date Sheet 2018

friv 10 said...


Gracias por compartir sus ideas con nosotros. Friv Games Gry Friv gracias por la detallada informaciĆ³n. Juegos Friv Gry Friv Friv Gracias por vuestras reacciones a las transmisiones que os han hecho. Friv Games Juegos Friv Acogemos con agrado los comentarios de los lectores.

SWAMI AYYAPPA said...

click here
know more
home page
can my pc run it
system requirements

SWAMI AYYAPPA said...

path of exile system requirements
path of exile requirements
path of exile pc requirements
requirements path of exile pc
path of exile pc system requirements

Sharon Wood said...
This comment has been removed by the author.
Eillen Sharma said...

Escorts in Gurgaon
Escorts in Gurgaon

Escorts in Kolkata
Escorts in Bangalore
Escorts in Mumbai

Eillen Sharma said...

Do you want call girls in Gurgaon or want to sleep with call girls in Gurgaon for a night ? Are you looking for call girls in Bangalore or want to hire call girls in Mumbai ?

Find Floor Plans said...

Friv - Juegos de futbol - Mapas Minecraft

Letras de Bts

rithiaanandh said...

I found this informative and interesting blog so I think so it's very useful and knowledgeable. I would like to thank you for the efforts you have made in writing this article.
Sql server dba online training

Find Floor Plans said...

Friv 2021

Mapas Minecraft


Letras de bts


Friv juegos

Banu Ravi said...

Great collection and thanks for sharing this info with us. Waiting for more like this.
Best AngularJS Training in Chennai
Angularjs Training institute in Chennai
AngularJS Training in Chennai
Angular 2 Training in Chennai
Angular 7 Training in Chennai
PHP Training in Chennai
Web Designing course in Chennai
AngularJS Training in Velachery
AngularJS Training in Vadapalani
AngularJS Training in Adyar

menyeng said...

I thank you for the information and articles you provided cara menggugurkan kandungan dan mempercepat haid

pkv games said...

dimasa pandemi ini keuangan semakin sulit. kunjungi kami untuk mainkan pkv games dari situs indodewaqq 180.215.200.34

Ayesha Bajaj said...

You can book call girl in Guwahati or escort Service in Guwahati for incall facility or
outcall Facility as and when required.To book Guwahati call girls you
can visit the following links
Guwahati Escorts
Call Girl in Guwahati

yanmaneee said...

jordan 4
michael jordan shoes
jordan shoes
hermes belt
supreme new york
curry 6
golden goose outlet
golden goose sneakers
yeezy
yeezy

Escorts Service Kolkata said...

escorts service in kolkata |
escorts service in kolkata |
escorts service in kolkata |
escorts service in kolkata |
escorts service in kolkata |

May said...

Technology News is a guide and recommendation blog on the most popular best switches , best sound card , best wifi adapters , best convertible laptops , best webcams technology this year.