當一個接口存在多個實現的時候會報org.springframework.beans.factory.NoUniqueBeanDefinitionException類似的異常信息,項目中碰到引用別人事先寫好的框架,但是對於其中個別實現並不是很需要,因此可以通過使用@Primary注解進行處理
比如處理登錄失敗時
@Component
public class OtherAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
public HcAuthenticationFailureHandler() {
}
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
if (exception instanceof SessionAuthenticationException) {
ResponseUtil.out(response, HttpStatus.UNAUTHORIZED, AjaxMessage.error("該賬戶登錄數量已達上限,請先下線別處的登錄!"));
} else {
ResponseUtil.out(response, HttpStatus.UNAUTHORIZED, AjaxMessage.error(exception.getMessage()));
}
}
}
我需要對返回的異常再進一步處理,@Primary指優先使用本處理器
@Primary
@Component
public class AuthenticationFailureHandler extends HcAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
if (exception instanceof SessionAuthenticationException) {
ResponseUtil.out(response, HttpStatus.UNAUTHORIZED, AjaxMessage.error("該賬戶登錄數量已達上限,請先下線別處的登錄!"));
} else {
if (exception instanceof ValidateLoginException && exception.getMessage().equals("賬戶不存在")) {
ResponseUtil.out(response, HttpStatus.UNAUTHORIZED, AjaxMessage.error("用戶名或密碼錯誤"));
} else {
ResponseUtil.out(response, HttpStatus.UNAUTHORIZED, AjaxMessage.error(exception.getMessage()));
}
}
}
}