1,自定义注解格式:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedJSONNullReplace {
}
2,注解实现类
public class JSONNullReplaceAdvice {
/**
* 用于在返回的时候,将jsonObject,jsonArray,ResultInfoVO中object中的jsonnull替换为“”;
* @param jp
* @param returnValue
* @throws Throwable
*/
public void afterReturning(JoinPoint jp, Object returnValue) throws Throwable {
if(returnValue instanceof JSONObject){
JSONObject obj = (JSONObject)returnValue;
returnValue = JSONUtil.JSONNullFilter(obj);
}else if(returnValue instanceof JSONArray){
JSONArray arr = (JSONArray)returnValue;
returnValue = JSONUtil.JSONNullFilter(arr);
}else if(returnValue instanceof ResultInfoVO){
Object obj = ((ResultInfoVO)returnValue).getObject();
if(obj instanceof JSONObject){
JSONObject jsonObj = (JSONObject)obj;
jsonObj = JSONUtil.JSONNullFilter(jsonObj);
}else if(obj instanceof JSONArray){
JSONArray jsonArr = (JSONArray)obj;
jsonArr = JSONUtil.JSONNullFilter(jsonArr);
}
}
}
}
3,面向切面配置
<bean id="jsonNullRepalceAdvice" class="com.yjcloud.annotation.JSONNullReplaceAdvice"/>
<aop:config>
<aop:pointcut expression="@annotation(com.yjcloud.annotation.NeedJSONNullReplace)" id="needJSONNullReplace"/>
<aop:aspect ref="jsonNullRepalceAdvice">
<aop:after-returning method="afterReturning" pointcut-ref="needJSONNullReplace" returning="returnValue"/>
</aop:aspect>
</aop:config>
4,特殊说明
@Target说明了Annotation所修饰的对象范围:
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
2,@Retention定义了该Annotation被保留的时间长短
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)
3,配置aop 相关参考
<aop:config>
<aop:aspect id="TestAspect" ref="aspectBean">
<!--配置com.spring.service包下所有类或接口的所有方法-->
<aop:pointcut id="businessService"
expression="execution(* com.spring.service.*.*(..))" />
<aop:before pointcut-ref="businessService" method="doBefore"/>
<aop:after pointcut-ref="businessService" method="doAfter"/>
<aop:around pointcut-ref="businessService" method="doAround"/>
<aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
</aop:aspect>
</aop:config>
5,使用:
只需要在要实现过滤的方法上加入@NeedJSONNullReplace 即可。
6,参考链接:http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html