Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I autowire named loggers?

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?

like image 957
Kojotak Avatar asked May 09 '13 14:05

Kojotak


People also ask

Can we do Autowired by name?

1) byName autowiring modeIn case of byName autowiring mode, bean id and reference name must be same. It internally uses setter injection. But, if you change the name of bean, it will not inject the dependency.

Which classes can be Autowired in spring?

In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file.

Can I Autowire any class?

The answer for your question is YES. You can use autowired in thread class.

What is difference between @bean and @autowire?

@Bean is just for the metadata definition to create the bean(equivalent to tag). @Autowired is to inject the dependancy into a bean(equivalent to ref XML tag/attribute).


1 Answers

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);
    }
}
like image 195
Javi M Avatar answered Sep 28 '22 18:09

Javi M