Search code examples
javamavenmaven-3maven-plugin

How to inject the Log dependency to a non Mojo class instance?


Is there a way to inject Log dependency to a non-Mojo class instance? In Mojo classes, we simply call getLog() whenever we want to log something, but what happens in the case of a service class?

Something like this one below does not work.

@Singleton
public class AServiceClass implements ServiceInterface {

    @Inject
    private Log log;
    ...
}

A simple way of solving this is to pass the log object from the Mojo class to the service method whenever we call it, but I don't want to do that.


Solution

  • So, thanks to maven-checkstyle-plugin, I was able to find the solution.

    You need to extend AbstractLogEnabled when you want to access the logger.

    @Singleton
    public class AServiceClass extends AbstractLogEnabled implements ServiceInterface {
    
        public void method(){
            // getLogger() gives you access to the logger
            getLogger().info(...)
        }
    }