Search code examples
javadependency-injectioncdi

java CDI injection how to annotate and modify third part class


I'm new to java CDI, I'm wondering how can I annotate a third party class when I inject it.

For example, I would like to inject jackson ObjectMapper into many of my services, and I would like to register some customized serializer, what I can do is write a method and mark as @PostConstruct but only when I can access its code. I think this scenario is quite common when injecting some third part class but would like to do some customization on them. What's a common practice in java CDI?


Solution

  • Write a producer.

    I use this often for creation of loggers like this:

    @ApplicationScoped
    public class LoggerProducer {
       @Produces
       public Logger getLogger(InjectionPoint ip) {
          // only include the injection point if you need it
          return LoggerFactory.getLogger(ip.getBean().getBeanClass().getSimpleName());
       }
    }
    
    ...
    
    @Inject
    private Logger logger;