Spring MethodInterceptor 使用
2021-03-05 20:27
标签:-- docker inf poi exe bean try location 模拟 ==================== 模拟一个需求, 接口调用时,打一下日志==================== 1. 定义一个注解 2. 实现method interceptor 接口 3. 新建一个配置文件 springContext.xml 4, 启动类加载配置文件 Spring MethodInterceptor 使用 标签:-- docker inf poi exe bean try location 模拟 原文地址:https://www.cnblogs.com/yangxijun/p/14320521.html1 @Target({ElementType.TYPE, ElementType.METHOD})
2 @Retention(RetentionPolicy.RUNTIME)
3 public @interface TraceLog {
4 }
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 }
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>
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ImportResource("classpath:springContext.xml")
public class DockerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(DockerDemoApplication.class, args);
}
}
文章标题:Spring MethodInterceptor 使用
文章链接:http://soscw.com/index.php/essay/60597.html