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?
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.
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.
The answer for your question is YES. You can use autowired in thread class.
@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).
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With