How do I inject a logger into a field in the sample spring boot application?
Solution using @Bean
:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class LoggerConfiguration {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Logger logger(InjectionPoint injectionPoint){
return LoggerFactory.getLogger(injectionPoint.getMethodParameter().getContainingClass());
}
}
After that, just inject the Logger using Constructor Injection (field injection will not work):
@Service
class SomeService {
private Logger logger;
public SomeService(Logger logger;) {
this.logger = logger;
}
public void someMethod() {
logger.error("Some log");
}
}
Although it is not the usual way you can add a logger bean directly in your context reproducing the classic bind:
private final Logger logger = LoggerFactory.getLogger(MainController.class);
simply inserting in the spring context:
<bean id="logger" scope="prototype" class="org.slf4j.LoggerFactory" factory-method="getLogger">
<constructor-arg name="name" value="youLoggerName" />
</bean>
then you can simply inject your logger:
@Autowired
private Logger logger;
If the objective here is code reduction then try Project Lombok. You then don't even need to declare the logger - just add an annotation and use log
instead of logger
So your above code will now look like this:
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
// import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Controller
public class MainController {
@RequestMapping("/")
public String enterSite(HttpServletResponse response) {
log.info("site entered");
return "welcome";
}
}