In our webapp we're using java.util.Logging (JULI, actually, since we deploy to T开发者_开发百科omcat 6). Logging is configured by a logging.properties file in WEB-INF/classes, a la this.
I'd like to configure the logger so it can be autowired, something like:
@Autowired
private Logger mylogger;
I've searched the Spring forums, the web, and of course Stack Overflow and I can't find how to set this up. I'd appreciate any help on this.
Thanks!
One way would be to use the Java Config style, so you'd have one bean like this:
@Configuration
public class LoggerProvider {
@Bean
public Logger logger() {
return Logger.getLogger("foobar.whatever");
}
}
That could then be autowired into the rest of the app as normal.
In order to use @Autowired on something (a bean) you must make that bean spring-controlled. There are many ways to do this and they depend on the logging framework you want to use.
I'm afraid there isn't a 'one-size-fits-all' solution.
Usually, you would use a static initializer provided by the logging framework of your choice or some abstraction over it (e.g. commons-logging).
I found one reference in which a @Logger annotation is introduced, maybe that points you into a direction of your liking:
http://jgeeks.blogspot.com/2008/10/auto-injection-of-logger-into-spring.html
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);
}
}
精彩评论