这段时间在重写接口测试框架,为了确保对核心业务做全面的校验,因此也增加了 快速登录这块功能

参考官方文档
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop

自定义注解 QuickLogin

package com.hero.common.annotation;

import java.lang.annotation.*;

/**
 * @Des: 自定义注解--用户快速登录
 * @Auther: 飞狐
 * @Date: 2019/2/1
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface QuickLogin {

    String name() default "";

    String password() default "";
}

AOP 切面

支持 token 过期 401 时,自动重新登录


@Aspect
@Component
public class UserQuickLoginAspect {

    private Log LOG = LogFactory.getLog(UserQuickLoginAspect.class);

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserAccountDAO userAccountDAO;

    @Autowired
    private CommonUserInfoService commonUserInfoService;

    @Before(value = "@annotation(quickLogin)")
    public Object doUserLogin(QuickLogin quickLogin) throws Throwable {
        String name = quickLogin.name();
        String password = quickLogin.password();
        Reporter.log("快速登录:" + name + "/" + password);

        LocalUserInfo localUserInfo = commonUserInfoService.getLocalUserInfo(name);

        if(null == localUserInfo){
            return commonUserInfoService.userLoginByPassword(convert2UserLoginRequestInfo(quickLogin));
        }

        Long userId = localUserInfo.getUserId();

        DynamicMethodDataSourceHolder.set(name,userId.toString());

        //试下head方法,确定不是401
        Result result = userInfoService.headUserProfile(name);

        MiniResponse miniResponse = (MiniResponse) result.getRes();

        if (miniResponse.getCode() != HttpStatus.OK.value()) {
            return commonUserInfoService.userLoginByPassword(convert2UserLoginRequestInfo(quickLogin));
        }
        return result;

    }


    private UserLoginRequestInfo convert2UserLoginRequestInfo(QuickLogin quickLogin){
        UserLoginRequestInfo userLoginRequestInfo = new UserLoginRequestInfo();
        userLoginRequestInfo.setUserName(quickLogin.name());
        userLoginRequestInfo.setPassword(quickLogin.password());
        userLoginRequestInfo.setAppSource(quickLogin.appSource());
        return userLoginRequestInfo;
    }


}

ThreadLocal 处理,主要减少本地文件读写,直接线程变量中进行处理

/**
 * 本地线程缓存变量,存储userId
 * Created by huqingen on 2018/6/26.
 */
public class DynamicMethodDataSourceHolder {

    public static final ThreadLocal<Map<String,String>> hodler = new ThreadLocal<>();


    public static Map<String,String> get(){
        return hodler.get();
    }

    public static void set(Map<String,String> map){
        hodler.set(map);
    }

    public static void set(String key,String value){
        Map<String,String> map = hodler.get();
        if(map == null){
            map = Maps.newHashMap();
        }

        map.put(key,value);
        set(map);
    }

    public static void clean(){
        hodler.remove();
    }

}


↙↙↙阅读原文可查看相关链接,并与作者交流