Java – autowire named loggers

autowiredjavaloggingspring

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?

Best Solution

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);
    }
}