【动态拦截@PostMapping注解,并且修改或新增value属性】

不仅可以拦截PostMapping 别的注解也可以



import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author:pys
 * @时间:2023年03月22日 14:14
 * @说明:动态修改RequestMapping注解
 */

@Slf4j
@Component
public class RequestMappingPrefixBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

  private static final String OLD_PREFIX = "/rest/rum";
  private static final String NEW_PREFIX = "/api/rum";
  private static final String VALUE = "value";
  private static final String MEMBER_VALUES = "memberValues";

  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
      throws BeansException {
    //获取RestController注解标注的bean
    String[] beanNames = beanFactory.getBeanNamesForAnnotation(RestController.class);
    for (String beanName : beanNames) {
      //获取Class
      Class<?> beanType = beanFactory.getType(beanName);
      //如果被RequestMapping标注
      if (beanType.isAnnotationPresent(RequestMapping.class)) {
        //获取注解
        RequestMapping annotation = beanType.getAnnotation(RequestMapping.class);
        //获取RequestMapping的所有路径
        String[] paths = annotation.value();
        List<String> newPathList = new ArrayList<>();
        //是否为 /rest/rum 开头的flag
        boolean addedNewPrefixFlag = false;
        String newPath = null;
        //遍历url路径
        for (String path : paths) {
          if (path.startsWith(OLD_PREFIX)) {
            log.info("old Annotation Value " + annotation.value()[0]);
            newPath = path.replace(OLD_PREFIX, NEW_PREFIX);
            //添加新的路径
            newPathList.add(newPath);
            addedNewPrefixFlag = true;
          }
          //添加老的路径
          newPathList.add(path);
          break;
        }
        //如果添加成功
        if (addedNewPrefixFlag && newPath != null) {
          //调转顺序 framework识别的是 path[0]的路径 所以要把/api/rum放前边 /rest/rum放后边
          newPathList.add(0, newPath);
          String[] newPaths = newPathList.toArray(new String[0]);
          Field f;
          try {
            //获取代理handler
            Object handler = Proxy.getInvocationHandler(annotation);
            //获取RequestMapping真正属性存值的地方
            f = handler.getClass().getDeclaredField(MEMBER_VALUES);
            f.setAccessible(true);
            Map<String, Object> memberValues;
            memberValues = (Map<String, Object>) f.get(handler);
            //替换value
            memberValues.put(VALUE, newPaths);
            log.info("New Annotation Value " + annotation.value()[0]);
          } catch (Exception e) {
            log.error("Failed to set annotation value: " + e.getMessage(), e);
          }
        }
      }
    }

  }
}

package com.joyintech.basicdata.mstquotemodelcfg.controller; import com.joyintech.basicdata.mstquotemodelcfg.service.MstQuoteModelCfgService; import com.joyintech.basicdata.mstquotemodelcfg.dao.entity.MstQuoteModelCfg; import com.psbc.pfpj.yoaf.response.RestResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** *@className MstQuoteModelCfgController *@description 债券一级投标报价模式配置 *@author 张立勃 *@date 2025/8/20 *@version 1.0 **/ @Api(tags = "债券一级投标报价模式配置") @RestController @RequestMapping(value = "/basic/mstquotemodelcfg") public class MstQuoteModelCfgController { @Resource private MstQuoteModelCfgService mstQuoteModelCfgService; @ApiOperation(value = "查看功能", notes = "查看功能") @GetMapping("/view") public RestResponse<MstQuoteModelCfg> viewById( @RequestParam(name = "id") @NotBlank(message = "id不能为空") String id, @RequestParam(name = "businesskey", required = false) String businesskey, @RequestParam(name = "businessno", required = false) String businessno) { return RestResponse.success(mstQuoteModelCfgService.viewById(id, businesskey, businessno),"查看功能成功"); } @ApiOperation(value = "新增更新功能", notes = "新增更新功能") @PostMapping("/save") public RestResponse<MstQuoteModelCfg> save( @RequestBody @NotNull(message = "MstQuoteModelCfg不能为空") MstQuoteModelCfg mstQuoteModelCfg) { return RestResponse.success(mstQuoteModelCfgService.saveData(mstQuoteModelCfg), "新增更新功能成功"); } @ApiOperation(value = "删除功能", notes = "删除功能") @PostMapping("/delete") public RestResponse<MstQuoteModelCfg> delete( @RequestBody @NotNull(message = "MstQuoteModelCfg不能为空") MstQuoteModelCfg mstQuoteModelCfg) { return RestResponse.success(mstQuoteModelCfgService.deleteData(mstQuoteModelCfg), "删除功能成功"); } } 后端代码如上:前端访问时报错{ "timestamp":1755746022491, "status":404, "error":"Not Found", "path":"/basic/mstquotemodelcfg/delete" }
最新发布
08-22
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值