Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI Injection and serialization

I'm considering to use CDI injection for slf4j logger, so I've created a producer.

I'm injecting it into an ApplicationScoped bean which is serializable:

@ApplicationScoped
public final class CurrentApplicationBean implements Serializable {
    @Inject
    private transient Logger          logger;
}

It must be transient because org.slf4j.Logger is an interface which doesn't extend Serializable, but this means that the logger must be re-injected after deserialization.

I think that CDI doesn't handle that, what's you knowledge?

Moreover, the provider always provides a new Logger instance beacuse it must set the logger name from the InjectionPoint, this means that RequestScoped beans have their own logger instance instead of a static per class logger.

Maybe logging is not a good context for CDI injection... what are your considerations?

like image 533
morphy76 Avatar asked Nov 13 '22 03:11

morphy76


1 Answers

but this means that the logger must be re-injected after deserialization.

The CDI Container proxy is serializable. When deserialized, the proxy locates/binds to the proper injection. I would not not mark the injection point as transient; as that would prevent the container to locate/rebind the injection and results in a NPE.

this means that RequestScoped beans have their own logger instance instead of a static per class logger

If your producer method is something like the following

@RequestScoped
@Produces   
public Logger produceLog(InjectionPoint injectionPoint) {   
    return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());   
}

The LoggerFactory.getLogger() is creating one logger per class.

Maybe logging is not a good context for CDI injection... what are your considerations?

It is your choice.

like image 127
apurohit Avatar answered Dec 28 '22 10:12

apurohit