Spring Boot 日志切面配置,java初级面试必问项目技术
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
public class LogConfig {
@Bean
@Profile("!prod") // 不是生产环境时生效
public WebMvcConfigurer logInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor());
}
};
}
private static class LogInterceptor extends LocaleChangeInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 在这里添加日志处理逻辑
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// 在这里添加日志处理逻辑
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// 在这里添加日志处理逻辑
}
}
}
这个代码示例展示了如何在Spring Boot项目中配置一个日志切面。它定义了一个LogInterceptor
类,继承自LocaleChangeInterceptor
,并重写了preHandle
、postHandle
和afterCompletion
方法以添加日志处理逻辑。@Profile("!prod")
注解确保这个配置只在非生产环境下生效。
评论已关闭