Custom Injections for Superclass Fields

121 views
Skip to first unread message

Chris Ward

unread,
Nov 20, 2009, 4:45:32 PM11/20/09
to google-guice
I am new to Guice and attempting to implement a logging example based
on this tutorial:
http://code.google.com/docreader/#p=google-guice&s=google-guice&t=CustomInjections

I would like to create an abstract base class with some utility
methods that include logging and then have subclasses reuse that
functionality. However, the Logger field in the superclass never gets
injected. Here is a simple example:

public abstract class AbstractServlet {

@InjectLogger Logger logger;

public void test1() {
logger.info("test1");
}
}

public class CustomServlet extends AbstractServlet {

public void test2() {
test1(); // Throws a NullPointerException for logger
}
}

After doing some more debugging it looks like the TypeListener never
gets called for the superclass field. I thought of passing a logger
using constructors, but that seems annoying to do for every class just
to get logging.

Can anyone give me a pointer on how to make this work or suggest a
better design practice?

Thanks,
Chris

limpb...@gmail.com

unread,
Nov 23, 2009, 11:51:17 AM11/23/09
to google-guice
On Nov 20, 1:45 pm, Chris Ward <chrisw1...@gmail.com> wrote:
> Can anyone give me a pointer on how to make this work or suggest a
> better design practice?

You should loop over the superclasses in the TypeListener.hear()
method:
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T>
typeEncounter) {
Class<?> raw = typeLiteral.getRawType();
for (Class<?> c = raw; c != Object.class; c = c.getSuperclass()) {
...
}
}

Chris Ward

unread,
Nov 23, 2009, 5:26:10 PM11/23/09
to google-guice
On Nov 23, 11:51 am, "je...@swank.ca" <limpbiz...@gmail.com> wrote:

> You should loop over the superclasses in the TypeListener.hear()
> method:

Ah, I kind of considered that, but wasn't sure of the code. Works
great.

Thanks for the help,
Chris
Reply all
Reply to author
Forward
0 new messages