spring經常使用接口之InitializingBean

spring經常使用接口簡介

InitializingBean接口

  • 做用:實現InitializingBean接口的bean,在初始化bean時都會執行afterPropertiesSet方法 afterPropertiesSespring

  • InitializingBean接口源碼以下:api

public interface InitializingBean {
    void afterPropertiesSet() throws Exception;
}
複製代碼
  • 使用實例:策略模式+InitializingBean
  • 業務場景:調用登陸接口後,須要根據接口返回的不一樣的錯誤碼,作出不一樣響應
  • 實現思路:將錯誤碼和場景實現類的映射關係,在bean初始化時經過afterPropertiesSet初試化至Map中(仿照spring初始化beandefinition),調用時經過調用接口返回的錯誤碼get到相應的實現類,InitializingBean在此場景中起到初始化map的做用
/**
 * 登陸場景抽象類
 *
 * @author xiantao.wu
 * @create 2019/5/1711:32
 **/
public abstract class AbstractScene implements InitializingBean {
    private static final Map<Integer, AbstractScene> SCENE_MAP = new ConcurrentHashMap<>();
    //初始化Map
    protected void register(Integer sceneType, AbstractScene scene) {
        SCENE_MAP.put(sceneType, scene);
    }


    public static AbstractScene getScene(Integer sceneType) {
        if (sceneType == null) {
            throw 業務異常
        }
        return SCENE_MAP.get(sceneType);
    }


    //調用統一入口
    public static AppLoginResponse checkLoginResponse(LoginResponse response) {
        Integer sceneType=response.getCode;
        AbstractScene scene = getScene(sceneType);
        if (scene == null) {
           throw 業務異常
        }

        return scene.check(apiResponse);
    }

    //登陸check項抽象方法
    public abstract AppLoginResponse check(ApiResponse<TokenPersonLoginResult> apiResponse);

}
複製代碼

具體實現類:bash

/**
 * 場景一:帳號存在風險
 *
 * @author xiantao.wu
 * @create 2019/5/1711:35
 **/
@Service
public class RiskAccountScene extends AbstractScene {
    @Autowired
    private PersonService personService;

    @Override
    public void afterPropertiesSet() throws Exception {
        register(Errors.RISK_ACCOUNT.getErrorCode(), this);
    }

    @Override
    public AppLoginResponse check(ApiResponse<TokenPersonLoginResult> apiResponse) {
        //TODO 具體實現邏輯
    }
}

/**
 * 場景二:須要驗證手機
 *
 * @author xiantao.wu
 * @create 2019/5/1711:35
 **/
@Service
public class NeedVerifyMobileScene extends AbstractScene {
    @Autowired
    private PersonService personService;

    @Override
    public void afterPropertiesSet() throws Exception {
        register(Errors.NEED_VERIFY_MOBILE.getErrorCode(), this);
    }

    @Override
    public AppLoginResponse check(ApiResponse<TokenPersonLoginResult> apiResponse) {
        //TODO 具體實現邏輯
    }
}


登陸調用

 /**
     * 登陸
     */
    @ApiOperation(value = "登陸", tags = "PASSPORT")
    @PostMapping(value = "/login")
    public ApiResponse<AppLoginResponse> login(@RequestBody AppLoginRequest appLoginRequest) {
        LoginResponse response = loginService.login(appLoginRequest);
        return ApiResponse.success(AbstractScene.checkLoginResponse(response));
    }

複製代碼
相關文章
相關標籤/搜索