Can I autowire named loggers?
Solution 1
You can inject it with @Inject and BeanFactoryPostProcessor
@Inject
Logger logger;
You can find more details here: Using java annotation to inject logger dependency
Solution 2
In order to make Logger be injectable with @Autowired
, you must have a configuration class where you have configured all the Beans with which you use @Autowired
. That class will be marked with @Configuration
. There you must put the following @Bean
in your configuration:
@Configuration
public class WebConfiguration {
@Bean
@Scope("prototype")
public Logger produceLogger(InjectionPoint injectionPoint) {
Class<?> classOnWired = injectionPoint.getMember().getDeclaringClass();
return LoggerFactory.getLogger(classOnWired);
}
}
Related videos on Youtube
Comments
-
Kojotak over 1 year
I'm using non static loggers named according to class name:
protected Logger logger = LoggerFactory.getLogger(getClass());
Can I configure spring in a way, that will set proper logger using @Autowired?
@Autowired protected Logger logger;
I can use factory-method for logger initialization, but I don't know how to pass the class name as an argument. For the setter-based dependency injection, spring has to know the class name, since it holds the reference to the bean. Can I access it somehow? Is there another way?
-
Kojotak almost 10 yearsI think that this is the correct answer. I have used spring's post processors for something else recently and from the backward perspective it is exactly what I was looking for.
-
granadaCoder over 4 yearsGreat answer. Asking nicely......it is so much easier to figure these out when the java examples contain all the important import statements listed, without "*".
-
granadaCoder over 4 yearsFor future readers: import org.springframework.beans.factory.InjectionPoint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.slf4j.Logger import org.slf4j.LoggerFactory;