Spring MethodInterceptor 使用


 

 

==================== 模擬一個需求, 接口調用時,打一下日志====================

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         <!--<aop:advisor pointcut="execution(* com.example.docker.service.impl.*.*(..))" advice-ref="myMethodInterceptor" />-->
13 
14         <!--<aop:advisor pointcut="@within(com.example.docker.annotation.TraceLog)" advice-ref="myMethodInterceptor" />-->
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);
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM