码迷,mamicode.com
首页 > 编程语言 > 详细

spring侵入代码的各种方式整理汇总

时间:2019-12-30 23:24:43      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:mes   main   方便   err   abi   strong   删除   ports   registry   

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 

配置 监听器:

  1. <listener>
  2.     <listener-class>web.CountListener</listener-class>
  3. </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侵入代码的各种方式整理汇总

标签:mes   main   方便   err   abi   strong   删除   ports   registry   

原文地址:https://www.cnblogs.com/thinkqin/p/11812082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!