Skip to content

Commit

Permalink
aop 接口上注解拦截支持 & 声明式aop使用姿势
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyueyi committed May 25, 2021
1 parent f91f543 commit d6fb8d6
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 41 deletions.
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ SpringBoot + SpringCloud + SpringSecurity学习过程中的源码汇总,沉淀
- [【基础系列】AOP之高级使用技能](http://spring.hhui.top/spring-blog/2019/03/02/190302-SpringBoot%E5%9F%BA%E7%A1%80%E7%AF%87AOP%E4%B9%8B%E9%AB%98%E7%BA%A7%E4%BD%BF%E7%94%A8%E6%8A%80%E8%83%BD/)
- [【基础系列】AOP之拦截优先级详解](http://spring.hhui.top/spring-blog/2019/03/10/190310-SpringCloud%E5%9F%BA%E7%A1%80%E7%AF%87AOP%E4%B9%8B%E6%8B%A6%E6%88%AA%E4%BC%98%E5%85%88%E7%BA%A7%E8%AF%A6%E8%A7%A3/)
- [【基础系列】AOP实现一个日志插件(应用篇)](http://spring.hhui.top/spring-blog/2019/03/13/190313-SpringCloud%E5%BA%94%E7%94%A8%E7%AF%87%E4%B9%8BAOP%E5%AE%9E%E7%8E%B0%E6%97%A5%E5%BF%97%E5%8A%9F%E8%83%BD/)
- [【基础系列】接口上注解AOP拦截不到场景兼容](https://spring.hhui.top/spring-blog/2021/05/25/210525-SpringBoot%E6%8E%A5%E5%8F%A3%E6%B3%A8%E8%A7%A3%E5%88%87%E9%9D%A2%E6%8B%A6%E6%88%AA%E4%B8%8D%E5%88%B0%E5%9C%BA%E6%99%AF%E5%85%BC%E5%AE%B9/)


**日志**

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@
@SpringBootApplication
public class Application {

public Application(PrintDemo printDemo, AnoDemo anoDemo, BaseApi baseApi) {
public Application(PrintDemo printDemo, AnoDemo anoDemo, BaseApi baseApi) throws InterruptedException {
// System.out.println(printDemo.genRand(10, "--一灰灰Blog"));
// System.out.println(anoDemo.gen("!23"));
// System.out.println("\n\n\n ----------- \n\n");

System.out.println(baseApi.print("hello world"));
System.out.println("-----------");
// System.out.println(baseApi.print2("hello world"));
for (int i = 0; i < 100; i++) {
System.out.println(baseApi.print("hello world"));
System.out.println("-----------\n\n");
}

System.out.println(baseApi.print2("hello world"));
}

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.alibaba.fastjson.JSON;
import lombok.Setter;
import lombok.SneakyThrows;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.ClassFilter;
Expand All @@ -13,7 +12,8 @@
import org.springframework.aop.support.annotation.AnnotationMethodMatcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;

Expand All @@ -22,7 +22,6 @@
* @date 2021/5/24
*/
@Configuration
@Component
public class ExtendLogAspect {

public static class LogAdvice implements MethodInterceptor {
Expand All @@ -42,55 +41,47 @@ public Object invoke(MethodInvocation methodInvocation) throws Throwable {
throw e;
} finally {
long end = System.currentTimeMillis();
System.out.println(req + "" + JSON.toJSONString(res) + SPLIT_SYMBOL + (end - start));
System.out.println("ExtendLogAspect:" + req + "" + JSON.toJSONString(res) + SPLIT_SYMBOL + (end - start));
}
}


private String buildReqLog(MethodInvocation joinPoint) {
StopWatch stopWatch = new StopWatch();
// 目标对象
stopWatch.start("getThis");
Object target = joinPoint.getThis();
stopWatch.stop();
// 执行的方法
stopWatch.start("getMethod");
Method method = joinPoint.getMethod();
stopWatch.stop();
// 请求参数
stopWatch.start("getArguments");
Object[] args = joinPoint.getArguments();
stopWatch.stop();

stopWatch.start("reflect");
StringBuilder builder = new StringBuilder(target.getClass().getName());
builder.append(SPLIT_SYMBOL).append(method.getName()).append(SPLIT_SYMBOL);
stopWatch.stop();
stopWatch.start("buildArgs");
for (Object arg : args) {
builder.append(JSON.toJSONString(arg)).append(",");
// builder.append(JSON.toJSONString(arg)).append(",");
builder.append(arg);
}
return builder.substring(0, builder.length() - 1) + SPLIT_SYMBOL;
}
}

public static class LogAdvisor extends AbstractBeanFactoryPointcutAdvisor {
@Setter
private Pointcut logPointCut;

@Override
public Pointcut getPointcut() {
return logPointCut;
String ans = builder.toString() + SPLIT_SYMBOL;
stopWatch.stop();
// System.out.println("ExtendLogAspect buildReqLog cost: " + stopWatch.prettyPrint());
return ans;
}
}

public static class LogPointCut extends StaticMethodMatcherPointcut {

@SneakyThrows
@Override
public boolean matches(Method method, Class<?> aClass) {

if (method.isAnnotationPresent(AnoDot.class)) {
return true;
}

for (Class in : aClass.getInterfaces()) {
try {
return in.getMethod(method.getName(), method.getParameterTypes()).isAnnotationPresent(AnoDot.class);
} catch (Exception e) {
}
}
return false;
return AnnotatedElementUtils.hasAnnotation(method, AnoDot.class);
}
}

Expand Down Expand Up @@ -119,12 +110,22 @@ public final MethodMatcher getMethodMatcher() {
}
}

public static class LogAdvisor extends AbstractBeanFactoryPointcutAdvisor {
@Setter
private Pointcut logPointCut;

@Override
public Pointcut getPointcut() {
return logPointCut;
}
}

@Bean
public LogAdvisor init() {
LogAdvisor logAdvisor = new LogAdvisor();
// 自定义实现姿势
// logAdvisor.setLogPointCut(new LogPointCut());
logAdvisor.setLogPointCut(new AnoPointCut());
logAdvisor.setLogPointCut(new LogPointCut());
// logAdvisor.setLogPointCut(new AnoPointCut());
logAdvisor.setAdvice(new LogAdvice());
return logAdvisor;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package com.git.hui.boot.aop.logaspect;

import com.alibaba.fastjson.JSON;
import com.git.hui.boot.aop.demo.PrintDemo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AdviceName;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;

Expand Down Expand Up @@ -47,18 +44,29 @@ public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable


private String buildReqLog(ProceedingJoinPoint joinPoint) {
StopWatch stopWatch = new StopWatch();
// 目标对象
stopWatch.start("getTarget");
Object target = joinPoint.getTarget();
stopWatch.stop();
// 执行的方法
stopWatch.start("getMethod");
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
stopWatch.stop();
// 请求参数
stopWatch.start("getArgs");
Object[] args = joinPoint.getArgs();
stopWatch.stop();

stopWatch.start("buildLog");
StringBuilder builder = new StringBuilder(target.getClass().getName());
builder.append(SPLIT_SYMBOL).append(method.getName()).append(SPLIT_SYMBOL);
for (Object arg : args) {
builder.append(JSON.toJSONString(arg)).append(",");
}
return builder.substring(0, builder.length() - 1) + SPLIT_SYMBOL;
String ans = builder.substring(0, builder.length() - 1) + SPLIT_SYMBOL;
stopWatch.stop();
System.out.println("LogAspect buildReqLog cost: " + stopWatch.prettyPrint());
return ans;
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
package com.git.hui.boot.jdbc;

import com.git.hui.boot.jdbc.api.TransApiImpl;
import com.git.hui.boot.jdbc.bean.DetailTransactionalSample;
import com.git.hui.boot.jdbc.bean.PropagationSample;
import com.git.hui.boot.jdbc.bean.TransactionalSample;
import com.git.hui.boot.jdbc.demo.NotEffectSample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

/**
* Created by @author yihui in 14:33 20/1/17.
*/
@SpringBootApplication
public class Application {
public Application(NotEffectSample notEffectSample, TransactionalSample transactionalSample,
DetailTransactionalSample detailTransactionalSample, PropagationSample propagationSample) throws Exception {
DetailTransactionalSample detailTransactionalSample, PropagationSample propagationSample,
TransApiImpl transApi, JdbcTemplate jdbcTemplate) throws Exception {
transactionalSample.testSimpleCase();
transactionalSample.testManualCase();

Expand All @@ -24,6 +27,13 @@ public Application(NotEffectSample notEffectSample, TransactionalSample transact

propagationSample.testPropagation();

try {
transApi.update(111);
} catch (Exception e) {
System.out.println(e.getMessage());
}

System.out.println(jdbcTemplate.queryForList("select * from money where id=111"));
}

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.git.hui.boot.jdbc.api;

import org.springframework.transaction.annotation.Transactional;

/**
* @author yihui
* @date 21/5/24
*/
public interface TransApi {

@Transactional(rollbackFor = Exception.class)
boolean update(int id);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.git.hui.boot.jdbc.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
* @author yihui
* @date 21/5/24
*/
@Service
public class TransApiImpl implements TransApi {
@Autowired
private JdbcTemplate jdbcTemplate;

@Override
public boolean update(int id) {
String sql = "replace into money (id, name, money) values (" + id + ", '事务测试', 200)";
jdbcTemplate.execute(sql);

Object ans = jdbcTemplate.queryForMap("select * from money where id = 111");
System.out.println(ans);

throw new RuntimeException("事务回滚");
}
}

0 comments on commit d6fb8d6

Please sign in to comment.