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

spring提供了很多方式更改代码的一些值,虽然非常方便,滥用容易不受控制,对代码阅读,后续维护产生一定的难度,这里整理下方式。

一 修改函数入参

argumentResolver

@Componentpublic 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";    }}
@SpringBootConfigurationpublic 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

@Componentpublic 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,举两个例子

@WebListenerpublic class ServletRequestListener implements javax.servlet.ServletRequestListener {    public void  requestDestroyed(ServletRequestEvent sre) {        System.out.println("listner "+sre.getServletContext().getAttributeNames().toString());    }}
//仅仅发布服务时被调用一次@WebListenerpublic 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

@Componentpublic 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
@ControllerAdvicepublic 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;    }}
@ControllerAdvicepublic 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;    }}

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

时间: 2024-10-07 18:03:15

spring侵入代码的各种方式整理汇总的相关文章

MyBatis概念性面试题整理汇总

MyBatis概念性面试题整理汇总 MyBatis常见的概念性面试题 一.概念性填空题 1.#{}和$ {}的区别是什么?#{}是_____,${}是_____. 2.四个核心接口是()用于执行CRUD操作.()处理SQL的参数.()处理返回结果集.()用于执行SQL语句. 3.MyBatis中提供了一级缓存和二级缓存,其中()默认存在,不可控制,同一SqlSession范围内的操作共享该缓存,增.删.改后将(). 4.Mybatis的Xml映射文件中,不同的Xml映射文件,id是否可以重复?

Spring 侵入式和非侵入式

1.非侵入式的技术体现 允许在应用系统中自由选择和组装Spring框架的各个功能模块,并且不强制要求应用系统的类必须从Spring框架的系统API的某个类来继承或者实现某个接口. 2.如何实现非侵入式的设计目标的 1)应用反射机制,通过动态调用的方式来提供各方面的功能,建立核心组间BeanFactory 2)配合使用Spring框架中的BeanWrapper和BeanFactory组件类最终达到对象的实例创建和属性注入 3)优点:允许所开发出来的应用系统能够在不用的环境中自由移植,不需要修改应用

ORACLE ERP相关整理汇总

摘自:http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece763104687270e54f7633f8883492c81c40884642c101a39feed7c63525483846b6777ac4f5aeefb3765377523a09bbfd20c82e5866d72c8713b2d5cd5104c840eafba11658337902bb6e947f0bb802594dac5d2af0b008c044521d3ae9c5b700

Spring Boot启动过程及回调接口汇总

Spring Boot启动过程及回调接口汇总 链接: https://www.itcodemonkey.com/article/1431.html 来自:chanjarster (Daniel Qian) 注:本文基于spring-boot 1.4.1.RELEASE, spring 4.3.3.RELEASE撰写. 启动顺序 Spring boot的启动代码一般是这样的: 1 2 3 4 5 6 @SpringBootApplication public class SampleApplica

spring security四种实现方式

spring security四种实现方式 标签: spring security spring spring(20) > 目录(?)[+] 最简单配置spring-securityxml实现1 实现UserDetailsService 实现动态过滤用户权限 实现AuthenticationProvider自定义参数验证 spring security实现方式大致可以分为这几种: 1.配置文件实现,只需要在配置文件中指定拦截的url所需要权限.配置userDetailsService指定用户名.

实现spring事务的四种方式

用一个银行账号转钱的案例来说明spring事务的实现.在转钱过程中,一个账号钱增加,另一个减少,那么当有异常产生时,就会出现钱转丢了的现象一个减少了,而另一个没有增加,这个时候就需要把这两个行为绑定到一起,要么同时发生,要么都不发生这就用到了事务,事务就是指在逻辑上的一组操作,这组操作要么全部成功,要么全部失败 实现spring事务的四种方式分别为:(1)编程式事务管理:需要手动编写代码,在实际开发中很少使用(2)声明式事务管理:(2.1)基于TransactionProxyFactoryBea

CC150 需整理汇总

汉诺塔问题:P141 用两个stack设计一个队列 p142 结合上题,队列实现max操作,要求尽量提高效率.(编程之美) 找出二叉树中指定节点的下一个节点(中序后继),假定每个节点有父指针.p154 二叉树某两个节点的公共祖先.p155 判断T2是否是T1的子树.p159 打印二叉树节点数值总和等于某个给定节点的所有路径. p161 打印0-1之间double数字的二进制表示 p164 编写一个函数,确定需要改变几个位,才能将整数A转成整数B.p171 9.3 寻找magic index.p2

Spring配置数据源的常用方式

Spring配置数据源的常用方式 在应用程序中配置数据源 (1).在classpath中创建连接参数的配置文件,如db-config.properties,内容如下: driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/zzp username=root password=admin (2).在Spring的配置文件中引入参数配置文件,代码如下: <!-- 配置spring资源文件 --> <bean id=

struts2和spring的两种整合方式

首先,来看看如何让Spring 来管理Action. 引入包struts2-spring-plugin-2.2.1.jar 配置 web.xml <!-- 指定spring的配置文件,主要配置spring为随着服务器启动而自启动,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 --> <context-param> <param-name>contextConfigLocation</param-name&