spring侵入代码的各种方式整理汇总
Posted thinkqin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring侵入代码的各种方式整理汇总相关的知识,希望对你有一定的参考价值。
spring提供了很多方式更改代码的一些值,虽然非常方便,滥用容易不受控制,对代码阅读,后续维护产生一定的难度,这里整理下方式。
一 修改函数入参
argumentResolver
@Component
public class HandlerMethodArgumentResolverDemo implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
if (methodParameter != null && methodParameter.getParameterType() == String.class && methodParameter.getParameterIndex() == 1) {
return true;
}
return false;
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
System.out.println("HandlerMethodArgumentResolverDemo");
return "set argument by HandlerMethodArgumentResolverDemo";
}
}
@SpringBootConfiguration
public class ConfigDemo extends WebMvcConfigurerAdapter {
@Autowired
IntercepterDemo intercepterDemo;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(intercepterDemo).addPathPatterns("/**");//配置拦截的路径,可以传多个参数
/*registry.addInterceptor(authorityInterceptor).addPathPatterns("/**");*/
}
@Autowired
HandlerMethodArgumentResolverDemo handlerMethodArgumentResolverDemo;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(handlerMethodArgumentResolverDemo);
}
}
二 interceptor
@Component
public class IntercepterDemo implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.addHeader("interceptaddhader","preintercepter");
System.out.println("IntercepterDemo preintecepter");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
response.addHeader("interceptaddhader","postintercepter");
if(modelAndView != null){
modelAndView.addObject("addObject");
}
System.out.println("IntercepterDemo postintecepter");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
System.out.println("IntercepterDemo afterCompletion");
}
}
上一个例子的 ConfigDemo 注册了这个intercepter
三.aop的方式
spring-aop ,aspectJ ,这个比较常用,先不说了
四 listener
普通web工程加listener:
Listener接口分类
1ServletContextListener监听ServletContext对象
> ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改
> HttpSessionListener监听Session对象
> HttpSessionActivationListener监听HTTP会话的active和passivate情况,passivate是指非活动的session被写入持久设备(比如硬盘),active相反。
> HttpSessionAttributeListener监听Session中的属性操作
> ServletRequestListener监听Request对象
> ServletRequestAttributeListener监听Requset中的属性操作
定义类 : public class CountListener implements HttpSessionListener
配置 监听器:
- <listener>
- <listener-class>web.CountListener</listener-class>
- </listener>
springboot 配置listener,举两个例子
@WebListener
public class ServletRequestListener implements javax.servlet.ServletRequestListener {
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("listner "+sre.getServletContext().getAttributeNames().toString());
}
}
//仅仅发布服务时被调用一次
@WebListener
public class ServletContextListenerDemo implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
System.out.println("listner "+sce.getServletContext().getAttributeNames().toString());
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
@SpringBootApplication
@ServletComponentScan(basePackages = "com.learn.filtertest")
public class MvntestApplication {
public static void main(String[] strings){
SpringApplication.run(MvntestApplication.class,strings);
}
}
五 filter
每个请求只执行一次的filter
@Component
public class OncePerRequestFilterDemo extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.addHeader("qzltest","yes");
System.out.println("OncePerRequestFilterDemo ,request uri is : " + httpServletRequest.getRequestURI());
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}
六 RequestBodyAdvice ReqponseBodyAdvice
@ControllerAdvice
public class RequestBodyAdviceDemo implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
//httpInputMessage.getBody().
System.out.println("RequestBodyAdviceDemo request body advice beforebodyread " + methodParameter.getMethod().getName());
return httpInputMessage;
}
@Override
public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
System.out.println("RequestBodyAdviceDemo request body advice afterbodyread " + methodParameter.getMethod().getName());
return o;
}
@Override
public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
System.out.println("RequestBodyAdviceDemo request body advice handler empty body " + methodParameter.getMethod().getName());
Class clazz = methodParameter.getParameterType();
if (clazz.equals(String.class)){
return "auto generate";
}
return o;
}
}
@ControllerAdvice
public class ResponseBodyAdviceDemo implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return methodParameter.getMethodAnnotations().length >= 1;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if(serverHttpResponse.getHeaders().containsKey("qzltest")){
System.out.println("ResponseBodyAdviceDemo response contains header qzl ,request uri is : " + serverHttpRequest.getURI());
}
if (o != null && o instanceof String){
return " add by class ResponseFilterDemo , string: "+ (String) o;
}
return o;
}
}
以上是关于spring侵入代码的各种方式整理汇总的主要内容,如果未能解决你的问题,请参考以下文章