SpringBoot基礎系列之AOP結合SpEL實現日誌輸出中兩點注意事項

【SpringBoot 基礎系列】AOP結合SpEL實現日誌輸出的注意事項一二

使用 AOP 來打印日誌大家一把都很熟悉了,最近在使用的過程中,發現了幾個有意思的問題,一個是 SpEL 的解析,一個是參數的 JSON 格式輸出

I. 項目環境

1. 項目依賴

本項目藉助SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA進行開發

開一個 web 服務用於測試

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

II. AOP & SpEL

關於 AOP 與 SpEL 的知識點,之前都有過專門的介紹,這裏做一個聚合,一個非常簡單的日誌輸出切面,在需要打印日誌的方法上,添加註解@Log,這個註解中定義一個key,作爲日誌輸出的標記;key 支持 SpEL 表達式

1. AOP 切面

註解定義

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    String key();
}

切面邏輯

@Slf4j
@Aspect
@Component
public class AopAspect implements ApplicationContextAware {
    private ExpressionParser parser = new SpelExpressionParser();
    private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    @Around("@annotation(logAno)")
    public Object around(ProceedingJoinPoint joinPoint, Log logAno) throws Throwable {
        long start = System.currentTimeMillis();
        String key = loadKey(logAno.key(), joinPoint);
        try {
            return joinPoint.proceed();
        } finally {
            log.info("key: {}, args: {}, cost: {}", key,
                    JSONObject.toJSONString(joinPoint.getArgs()),
                    System.currentTimeMillis() - start);
        }
    }

    private String loadKey(String key, ProceedingJoinPoint joinPoint) {
        if (key == null) {
            return key;
        }

        StandardEvaluationContext context = new StandardEvaluationContext();

        context.setBeanResolver(new BeanFactoryResolver(applicationContext));
        String[] params = parameterNameDiscoverer.getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(params[i], args[i]);
        }

        return parser.parseExpression(key).getValue(context, String.class);
    }

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

上面這個邏輯比較簡單,和大家熟知的使用姿勢沒有太大的區別

2. StandardEvaluationContext 安全問題

關於StandardEvaluationContext的注入問題,有興趣的可以查詢一下相關文章;對於安全校驗較高的,要求只能使用SimpleEvaluationContext,使用它的話,SpEL 的能力就被限制了

如加一個測試

@Data
@Accessors(chain = true)
public class DemoDo {

    private String name;

    private Integer age;
}

服務類

@Service
public class HelloService {

    @Log(key = "#demo.getName()")
    public String say(DemoDo demo, String prefix) {
        return prefix + ":" + demo;
    }
}

爲了驗證SimpleEvaluationContext,我們修改一下上面的loadKeys方法

private String loadKey(String key, ProceedingJoinPoint joinPoint) {
    if (key == null) {
        return key;
    }

    SimpleEvaluationContext context = new SimpleEvaluationContext.Builder().build();
    String[] params = parameterNameDiscoverer.getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
    Object[] args = joinPoint.getArgs();
    for (int i = 0; i < args.length; i++) {
        context.setVariable(params[i], args[i]);
    }

    return parser.parseExpression(key).getValue(context, String.class);
}

啓動測試

@SpringBootApplication
public class Application {

    public Application(HelloService helloService) {
        helloService.say(new DemoDo().setName("一灰灰blog").setAge(18), "welcome");
    }

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

直接提示方法找不到!!!

3. gson 序列化問題

上面的 case 中,使用的 FastJson 對傳參進行序列化,接下來我們採用 Gson 來做序列化

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

然後新增一個特殊的方法

@Service
public class HelloService {
    /**
     * 字面量,注意用單引號包裹起來
     * @param key
     * @return
     */
    @Log(key = "'yihuihuiblog'")
    public String hello(String key, HelloService helloService) {
        return key + "_" + helloService.say(new DemoDo().setName(key).setAge(10), "prefix");
    }
}

注意上面方法的第二個參數,非常有意思的是,傳參是自己的實例;再次執行

public Application(HelloService helloService) {
    helloService.say(new DemoDo().setName("一灰灰blog").setAge(18), "welcome");

    String ans = helloService.hello("一灰灰", helloService);
    System.out.println(ans);
}

直接拋了異常

這就很尷尬了,一個輸出日誌的輔助工具,因爲序列化直接導致接口不可用,這就不優雅了;而我們作爲日誌輸出的切面,又是沒有辦法控制這個傳參的,沒辦法要求使用的參數,一定能序列化,這裏需要額外注意 (比較好的方式就是簡單對象都實現 toString,然後輸出 toString 的結果;而不是 json 串)

4. 小結

雖然上面一大串的內容,總結下來,也就兩點

  • SpEL 若採用的是SimpleEvaluationContext,那麼注意 spel 的功能是減弱的,一些特性不支持
  • 若將方法參數 json 序列化輸出,那麼需要注意某些類在序列化的過程中,可能會拋異常

(看到這裏的小夥伴,不妨點個贊,順手關注下微信公衆號”一灰灰 blog“,我的公衆號已經寂寞的長草了 😭)

III. 不能錯過的源碼和相關知識點

0. 項目

AOP 系列博文

1. 一灰灰 Blog

盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現 bug 或者有更好的建議,歡迎批評指正,不吝感激

下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛

一灰灰blog

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章