Spring Inject Logger using Annotation

The Spring Inject Logger using Annotation tutorial shows you how to inject a logger with custom annotation. This tutorial helps you inject a logger into anywhare you want it. You will get the benefits in the testing work and operating application.

Logger Dependencies

In this Spring Inject Logger using Annotation tutorial, we are using two dependencies: slf4j logger interface and log4j logger implementation.

Notice: in the demo application, we will add the spring dependencies. You can see the detail in the complete source code.

Configure Spring with Java Annotation
We use Spring Java Configuration to configure our spring beans.

Create custom annotation
We will create a new @MyLogger annotation like below.

Spring Inject Logger using Annotation

Now, we can use the @MyLogger annotation at field level to inject a Logger.

Create MyLoggerInjector

The above @MyLogger injection is only the declaration on a field that we want to inject a Logger bean on that field. Next, we have to initialize that bean while Spring initialize a bean for the parent class. To do that, we implement the BeanPostProcessor interface which gives us the postProcessBeforeInitialization to manage a bean before initialization. And we inject an implementation with the LoggerFactory manually by searching for the @MyLogger annotation and initialize that bean. The below is detail implemenation.

Configure Log4j2 xml
Add the log4j2.xml with the below content to project classpath.

Demo Application

In this Spring Inject Logger using Annotation, we create demo application to test what we share above. First we create main class to bootstrap spring configuration. Then we call the service.

Run the above main, the output will print the logging information:

That’s all on the Spring Inject Logger using Annotation tutorial.

BeanPostProcessor JavaDoc

Download complete source code, click link below

spring-inject-logger-using-annotation.zip (276 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons