@ControllerAdvice

来源:互联网 发布:comparebeyond4 mac 编辑:程序博客网 时间:2024/04/28 04:53

源码

package org.springframework.web.bind.annotation;import java.lang.annotation.Annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.stereotype.Component;/** * 用来标志一个类,用来增强controller. * 被注解的类,能够被<context component-scan>自动扫描到 * 它通常被用于定义 @ExceptionHandler@InitBinder和ModelAttribute * 调用所有的被@RequestMapping标记的类之前,注解类中方法会被先执行(相当于spring的aop,一个过滤器) * 如果没有定义需要支援的controller的范围,则默认支援所有能扫描的controller */@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface ControllerAdvice {    /**     * @basePackages()属性的缩写.     * 允许扫描的包的集合。     * 格式1:@ControllerAdvice("org.my.pkg")     * 格式2:@ControllerAdvice(basePackages="org.my.pkg").     */    String[] value() default {};    /**     * 这些包下的Controllers 将会被增强。     * 格式1:@ControllerAdvice(basePackages="org.my.pkg")     * 格式2:@ControllerAdvice(basePackages={"org.my.pkg","org.my.other.pkg"})     * value()属性是它的缩写.     */    String[] basePackages() default {};    /**     * 增强引用指定类或接口的包名     *      */    Class<?>[] basePackageClasses() default {};    /**     * 增强指定类型的controllers     */    Class<?>[] assignableTypes() default {};    /**     * 增强被特定注解标记的controllers     */    Class<? extends Annotation>[] annotations() default {};}

处理异常的实例:

import com.google.gson.Gson;import com.google.gson.GsonBuilder;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.ResponseStatus;import com.exodus.weistore.data.*;import com.exodus.weistore.exception.WebException;//增强被@Controller标记的controller@ControllerAdvice(annotations = Controller.class)publict ControllerAdviceTest(){    private static Log log = LogFactory.getLog(ControllerAdviceTest.class);    public WebExceptionAdvice()    {        System.out.println("WebExceptionAdvice");    }    //处理异常    @ResponseBody    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)    @ExceptionHandler(WeistoreException.class)    public String HandleWebException(Exception exception){        log.error("WebException@WebExceptionAdvice", exception);        //新建json        Gson gson = new GsonBuilder()            .registerTypeAdapter(Timestamp.class, new TimestampAdapter()).create();        Response<Object> response = new Response<Object>();        response.setStatus(500);        response.setMessage(exception.toString());        return gson.toJson(response);        }}

response对象

package com.exodus.weistore.data;import java.io.Serializable;public class Response<T>    implements Serializable{    private static final long serialVersionUID = 2318866198328783813L;    private Integer status = 200;    private String message = "";    private T result;    public Integer getStatus()    {        return status;    }    public void setStatus(Integer status)    {        this.status = status;    }    public String getMessage()    {        return message;    }    public void setMessage(String message)    {        this.message = message;    }    public T getResult()    {        return result;    }    public void setResult(T result)    {        this.result = result;    }}

定义的异常:WeistoreException

package com.exodus.weistore.exception;import com.exodus.weistore.data.Response;public class WeistoreException    extends RuntimeException{    private static final long serialVersionUID = 1337477185117468301L;    public static final int ERROR_NO_PAYWAY = 440;    private int status;    private String message;    //constructor    public WeistoreException(int status, String message)    {        this.status = status;        this.message = message;    }    //to Response对象    public Response<Object> toResponse()    {        Response<Object> response = new Response<Object>();        response.setStatus(status);        response.setMessage(message);        return response;    }    //Getter And Setter    public int getStatus()    {        return status;    }    public void setStatus(int status)    {        this.status = status;    }    public String getMessage()    {        return message;    }    public void setMessage(String message)    {        this.message = message;    }}
0 0