Custom annotations cooperate with interceptors to complete interface service interception.

There is a requirement that you can configure and use pre-processed data instead of returning the original business logic data through the original service code.

In order not to damage the original code, I used custom annotations + interceptors

Custom annotations are as follows

// 可用在方法名上
@Target({ElementType.METHOD})
// 运行时有效
@Retention(RetentionPolicy.RUNTIME)
public @interface PreData {
    /**
     * 此处value为screen_info的Id
     */
    String value() ;

}

Then add the interceptor

public class DataInterceptor implements HandlerInterceptor {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    //此处为拦截用的的Service,实现拦截后逻辑
    @Autowired
    private YourService yourService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        PreData preDataAnnotation = method.getAnnotation(PreData.class);
        if (preDataAnnotation != null) {
            String value= preDataAnnotation.value();
            respData = yourService.do(value);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out;
            out = response.getWriter();
            Map<String, Object> resp = new HashMap<>(3);
            resp.put("msg", "操作成功");
            resp.put("code", 200);
            resp.put("data",respData);
            out.append(OBJECT_MAPPER.writeValueAsString(resp));
            return false;
        }
        return true;
    }
}

and register the interceptor

@Configuration
public class WebConfig implements WebMvcConfigurer {
    /**
     * 将拦截器作为bean写入配置中 不然拦截器的service会注入失败
     */
    @Bean
    public DataInterceptor dataInterceptor() {
        return new DataInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注意,此处添加的Bean为上面实例化时的bean 而不是new DataInterceptor
        registry.addInterceptor(dataInterceptor())
                .addPathPatterns("/**");
    }


}

At this time, add before Controller

Just @PreData

Guess you like

Origin blog.csdn.net/qq_25484769/article/details/121676417