Spring自定义注解

1、注解类

package com.springboot.annotationTest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by xp on 2020-12-08.
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface check {}

2、普通方法类

package com.springboot.annotationTest;
/**
 * Created by xp on 2020-12-08.
 */
public class Cal {

    @check
    public void add() {
        System.out.println("1+2=" + (1 + 2));
    }

    @check
    public void div() {
        System.out.println("1/0=" + (1 / 0));
    }
}

3、逻辑判断类

package com.springboot.annotationTest;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by xp on 2020-12-08.
 */
public class test {
    public static void main(String[] args) throws IOException {
        Cal cal = new Cal();
        Class aClass = cal.getClass();
        Method[] methods = aClass.getMethods();
        BufferedWriter bw = new BufferedWriter(new FileWriter("error.txt"));
        int num=0;
        for (Method method : methods) {
            if (method.isAnnotationPresent(check.class)) {
                try {
                    Object o = method.invoke(cal);
                } catch (Exception e) {
                    num++;
                    bw.write("异常名称:"+e.getCause().getClass().getSimpleName());
                    bw.write("{}方法异常"+method.getName());
                    e.printStackTrace();
                }
            }
        }
        bw.write("异常次数:"+num);
        bw.flush();
        bw.close();
    }
}

##逻辑判断部分的代码可以通过切面的方式进行改造

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值