java元注解+拦截器实现自定义注解(自定义依赖注入)

java元注解+拦截器实现自定义注解

demo代码下载 java元注解+拦截器实现自定义注解
元注解说明 java 四种元注解@Target、@Retention、@Documented 和@Inherited
@CmwAutoWired:自定义依赖注入 注意:注入的接口和实现类需要在同一包名下,注解的是类则无限制
@FieldAnnotation:自定义属性注解
@MethodAnnotation:自定义方法注解
@MethodParam:自定义方法参数注解

1.web MVC配置

/**
 * 描述:
 * web mvc配置
 * @author 闲走天涯
 * @create 2021/8/14 17:50
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    /**
     * 避免静态资源被拦截
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        String os = System.getProperty("os.name");//运行系统类型: Windows系统
        registry.addResourceHandler("/templates/**.js").addResourceLocations("classpath:/templates/");
        registry.addResourceHandler("/templates/**.css").addResourceLocations("classpath:/templates/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    /**
     * 设置字符集
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //设置字符集
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    /**
     * 注册 自定义注解拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new InterfaceInterceptor()).addPathPatterns("/feign/**","/testInt/**","/test/**")
                .excludePathPatterns("/login","/","/user/login");
    }
}

2.自定义注解 验证工具类

/**
 * 描述:
 * 自定义注解 验证工具类
 * @author 闲走天涯
 * @create 2021/8/16 13:57
 */
public class InterfaceUtil {

    /**
     * 自定义注解
     * 验证方法注解
     * @param obj
     */
    public static boolean method(HttpServletRequest request,Object obj) {
        try {
            Class clazz = obj.getClass();
            //获取所有声明的属性
            Method[] declaredMethods = clazz.getDeclaredMethods();
            //过滤出所有带有注解的属性
            List<Method> methodList = new ArrayList<>();
            for (Method method : declaredMethods) {
                //判断该接口所在的类的方法上是否存在注解 @FieldAnnotation
                if (method.isAnnotationPresent(MethodAnnotation.class)) {
                    //验证方法注解@FieldAnnotation
                    checkMethodAnnotation(obj,method);
                }
                //获取方法下的所有参数
                Parameter[] parameters = method.getParameters();
                for(Parameter param : parameters){
                    //判断是否存在参数注解 @MethodParam
                    if(param.isAnnotationPresent(MethodParam.class)){
                        //验证方法参数注解@MethodParam
                        checkMethodParam(request,param);
                    }
                }
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 自定义注解
     * 验证属性注解
     * @param obj
     */
    public static boolean field(Object obj) {
        try {
            Class clazz = obj.getClass();
            //获取所有声明的属性
            Field[] declaredFields = clazz.getDeclaredFields();
            //过滤出所有带有注解的属性
            List<Field> fields = new ArrayList<>();
            for (Field field : declaredFields) {
                //允许访问私有变量
                field.setAccessible(true);
                //判断该接口所在的类的属性上是否存在注解 @FieldAnnotation
                if (field.isAnnotationPresent(FieldAnnotation.class)) {
                    //验证属性注解@FieldAnnotation
                    checkFieldAnnotation(obj,field);
                }
                if(field.isAnnotationPresent(CmwAutoWired.class) && field.get(obj)==null){
                    //验证成员变量 依赖注入注解@CmwAutoWired
                    checkCmwAutoWired(obj, field);
                }
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 验证成员变量依赖注入注解 @CmwAutoWired
     * @param obj
     * @param field
     * @throws Exception
     */
    private static void checkCmwAutoWired(Object obj,Field field) throws Exception{
        CmwAutoWired annotation = field.getAnnotation(CmwAutoWired.class);
        String name = field.getType().getName();
        //获取注解的成员变量的类
        Class clazz = Class.forName(name);
        //判断注解的类是否属于接口
        //注解接口
        if(clazz.isInterface()){
            Class imClazz = null;
            //获取当前访问接口所在类的包对象
            Package clazzPackage = clazz.getPackage();
            //获取包名 com.interceptor.field
            String pk = clazzPackage.getName();
            String path = pk.replace('.', '/');
            //扫描包中所有的文件
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            URL url = classloader.getResource(path);
            File file = new File(url.getPath());
            //获取文件对象数组并删选其中的class文件
            File[] fileList = file.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    if(pathname.getName().contains(".class")){
                        return true;
                    }
                    return false;
                }
            });
            List<Class> classList = new ArrayList<>();
            //遍历 包中所有类
            for(File f : fileList){
                try {
                    //获取类对象
                    String cUrl = f.getName().replace(".class","");
                    String className = clazz.getName().replace(clazz.getSimpleName(),cUrl);
                    Class aClass = Class.forName(className);
                    //获取类所实现的接口
                    Class[] classes = aClass.getInterfaces();
                    for(Class c : classes){
                        //判断接口名是否等于注解的接口
                        if(c.getName().equals(clazz.getName())){
                            classList.add(aClass);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            //获取首个与注解接口名相同的接口
            if(classList!=null && classList.size()>0){
                imClazz = classList.get(0);
            }
            if(imClazz==null){
                throw new RuntimeException("注入失败,当前包下无接口的实现类");
            }else{
                //判断是否已经加载注入,如果无则注入一个接口实现类的实例
                if(field.get(obj)==null){
                    field.set(obj, imClazz.newInstance());
                }
            }
        }else{
            //注解类
            //判断是否已经加载注入,如果无则注入一个接口实现类的实例
            if(field.get(obj)==null){
                field.set(obj, clazz.newInstance());
            }
        }
    }

    /**
     * 验证属性注解 TestAnnotation
     * @param obj
     * @param field
     * @throws Exception
     */
    private static void checkFieldAnnotation(Object obj,Field field) throws Exception{
        FieldAnnotation annotation = field.getAnnotation(FieldAnnotation.class);
        //判断是否已经注入值,无则使用默认的值
        if(field.get(obj)==null) {
            field.set(obj, annotation.value());
        }
        //判断是否为空
        if(annotation.isNotNull() && ("".equals(annotation.value()) || annotation.value()==null)){
            throw new RuntimeException("field "+field.getName()+" Cannot be null");
        }
        if(annotation.value()!=null && !"".equals(annotation.value())){
            //判断长度是否大于
            if(annotation.value().length()>annotation.maxLength()){
                throw new RuntimeException("field "+field.getName()+" length Cannot be longer than "+annotation.maxLength());
            }
            //判断长度是否小于
            if(annotation.value().length()<annotation.minLength()){
                throw new RuntimeException("field "+field.getName()+" length Cannot be less than "+annotation.minLength());
            }
        }
    }

    /**
     * 验证属性注解 MethodAnnotation
     * @param obj
     * @param method
     * @throws Exception
     */
    private static void checkMethodAnnotation(Object obj,Method method) throws Exception{
        MethodAnnotation annotation = method.getAnnotation(MethodAnnotation.class);
        //获取注解的值
        Class getclazz = annotation.clazz();
        String getmethod = annotation.method();
        Class[] parameterTypes = annotation.parameterTypes();
        // 注解clazz属性 新建对象的实例
        Object getobj = getclazz.newInstance();
        //获取clazz属性 对象的 method属性方法
        Method getclazzMethod = getclazz.getMethod(getmethod,parameterTypes);
        //执行该方法
        Object result = getclazzMethod.invoke(getobj);
        System.out.println("输出:"+result.toString());
    }

    /**
     * 验证属性注解 MethodAnnotation
     * @param request
     * @param param
     * @throws Exception
     */
    private static void checkMethodParam(HttpServletRequest request,Parameter param) throws Exception{
        //获取注解对象
        MethodParam annotation = param.getAnnotation(MethodParam.class);
        //获取参数的值
        Object value = request.getParameter(param.getName());
        if(value==null){
            if(annotation.require()){
                throw new RuntimeException("param " + param.getName() + " Cannot be null");
            }
        }else {
            if (value instanceof String) {
                String str = (value != null ? String.valueOf(value) : "");
                if (annotation.require() && ("".equals(str) || str == null)) {
                    throw new RuntimeException("param " + param.getName() + " Cannot be null");
                }
                //判断长度是否大于
                if (str.length() > annotation.maxLength()) {
                    throw new RuntimeException("param " + param.getName() + " length Cannot be longer than " + annotation.maxLength());
                }
                //判断长度是否小于
                if (str.length() < annotation.minLength()) {
                    throw new RuntimeException("param " + param.getName() + " length Cannot be less than " + annotation.minLength());
                }
            }
        }
    }

}

3.自定义注解 拦截器

/**
 * 描述:
 * 自定义注解 拦截器
 * @author 闲走天涯
 * @create 2021/8/16 13:57
 */
@Component
public class InterfaceInterceptor extends HandlerInterceptorAdapter {
    /**
     * 在请求处理之前进行调用(Controller方法调用之前)
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("进入 Controller 某个方法之前");
        //获取接口所在类的bean
        HandlerMethod handlerMethod = ((HandlerMethod) handler);
        Object obj = handlerMethod.getBean();
        //开启执行属性注解验证
        if (!InterfaceUtil.field(obj)) {
            return false;
        }
        //开启执行方法注解验证
        if (!InterfaceUtil.method(request, obj)) {
            return false;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        System.out.println("类名:" + obj.getClass().getName());
        System.out.println("方法名:" + method.getName());
        try {
            request.setAttribute("startTime", new Date().getTime());
            if (true) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("TimeInterceptor 运行 Controller 某个方法时,方法抛出异常将不进入此方法");
        long start = (long) request.getAttribute("startTime");
        System.out.println("TimeInterceptor 处理时长为:" + (new Date().getTime() - start));
    }

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        System.out.println("TimeInterceptor 完成 Controller 某个方法");
        long start = (long) request.getAttribute("startTime");
        System.out.println("TimeInterceptor 处理时长为:" + (new Date().getTime() - start));
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response,
                                               Object handler) throws Exception {
        System.out.println("TimeInterceptor 执行 afterConcurrentHandlingStarted");
    }
}

4.注解声明

/**
 * @program: test
 * @description: 自定义依赖注入 注意:注入的接口和实现类需要在同一包名下,注解的是类则无限制
 * @author: 闲走天涯
 * @create: 2021-08-17 17:30
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CmwAutoWired {
}

/**
 * 描述:
 * 自定义属性注解
 * @author 闲走天涯
 * @create 2021/4/9 16:18
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
    String value() default "";
    boolean isNotNull() default false;
    int maxLength() default 100;
    int minLength() default 0;
}
/**
 * 描述:
 * 方法注解
 * @author 闲走天涯
 * @create 2021/4/10 15:42
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodAnnotation {
    String module() default "";


    /**
     * 方法执行前执行的类名
     * @return
     */
    Class clazz();
    /**
     * 方法执行前执行的方法名
     * @return
     */
    String method() default "";
    /**
     * 方法参数
     * @return
     */
    Class[] parameterTypes() default {};
}
/**
 * @program: test
 * @description: 自定义方法参数校验注解
 * @author: 闲走天涯
 * @create: 2021-08-18 17:02
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodParam {
    boolean require() default true;
    int maxLength() default 20;
    int minLength() default 0;
}

5.测试

/**
 * 描述:
 * 测试接口
 * @author 闲走天涯
 * @create 2021/4/9 14:18
 */
@RestController
@RequestMapping("/test")
public class FieldController implements LoginFace {

    @FieldAnnotation(value = "123456aaa",isNotNull = true)
    private String testInt;

    @CmwAutoWired
    public CmwDaoImpl cmwDao;

    @Override
    @RequestMapping("/testInt")
    public String testInt(){
        return "获取属性:" + testInt;
    }


    @RequestMapping("/getout")
    public String getout(){
        return "获取属性:" + cmwDao.getOut();
    }

    @RequestMapping("/tostring")
    public String tostring(){
        return "获取属性:" + cmwDao.toString();
    }
}
/**
 * 描述:
 * 测试接口
 * @author 闲走天涯
 * @create 2021/4/10 15:44
 */
@RestController
@RequestMapping("/test")
public class MainTestController {
    @CmwAutoWired
    private LoggerApply loggerApply;

    @RequestMapping("/out")
    @MethodAnnotation(clazz = CmwDaoImpl.class,method = "toString")
    public String test(@MethodParam(require = true,maxLength = 5,minLength = 1) String module) throws Exception{
        try {
            loggerApply.lingLogger(module);
            return "success";
        }catch (Exception e){
            return "faild";
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值