Spring MethodInterceptor 使用

2021-03-05 20:27

阅读:606

标签:--   docker   inf   poi   exe   bean   try   location   模拟   

技术图片

 

 

==================== 模拟一个需求, 接口调用时,打一下日志====================

1.  定义一个注解

1 @Target({ElementType.TYPE, ElementType.METHOD})
2 @Retention(RetentionPolicy.RUNTIME)
3 public @interface TraceLog {
4 }

2.  实现method interceptor 接口

 1 @Slf4j
 2 public class MyMethodInterceptor implements MethodInterceptor {
 3     @Override
 4     public Object invoke(MethodInvocation invocation) throws Throwable {
 5         try {
 6             Object result = invocation.proceed();
 7             log.info("MyMethodInterceptor interceptor...." + invocation.getMethod());
 8             return result;
 9         } catch (Exception e) {
10             log.info("MyMethodInterceptor interceptor...." + e);
11             throw  e;
12         }
13     }
14 }

 

3. 新建一个配置文件  springContext.xml

 1 xml version="1.0" encoding="UTF-8"?>
 2 beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:aop="http://www.springframework.org/schema/aop"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 6        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
 7 
 8     bean id="myMethodInterceptor" class="com.example.docker.aop.MyMethodInterceptor"/>  // 注入自定义的interceptor
 9 
10 
11     aop:config>
12         
13 
14         
15 
16         aop:advisor pointcut="@annotation(com.example.docker.annotation.TraceLog)" advice-ref="myMethodInterceptor" />   // within 和 @within 的区别,后者时对于注解来说的。  @within 和 @anntation区别 后者是方法级别,前者为类级别
17         
18     aop:config>
19 beans>

4,   启动类加载配置文件

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ImportResource("classpath:springContext.xml")
public class DockerDemoApplication {

    public static void main(String[] args) {
       SpringApplication.run(DockerDemoApplication.class, args);
    }

}

Spring MethodInterceptor 使用

标签:--   docker   inf   poi   exe   bean   try   location   模拟   

原文地址:https://www.cnblogs.com/yangxijun/p/14320521.html


评论


亲,登录后才可以留言!