和Java狼狈为奸
2018-11-07 11:46
采纳率: 61.5%
浏览 8.0k
已采纳

Spring boot 如何执行Controller中的初始化方法

我有一个BaseController.java 类,所有其他类继承该BaseController,如下

 public class BaseController {
        private HttpServletRequest request;
    private HttpServletResponse response;

        public void init(HttpServletRequest request, HttpServletResponse response) {
            this.request = request;
                this.response = response;
        }
 }

我的目的是要每次请求进入具体Controller之前先掉用init方法。这个有没有可行性啊。(PS:我尝试过用拦截器,但实现不了)

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 帅粑粑不好当 2018-11-07 12:25
    已采纳

    可以是可以不过有点限制,做一个切面就可以

    
    @RestController
    public class TestController extends  BaseController{
    
    
        @GetMapping("/get")
        public String gettest(HttpServletRequest request, HttpServletResponse response,String id){
    
            return "测试是否调用"+id;
    
        }
    
    }
    

    public class BaseController {
    private HttpServletRequest request;
    private HttpServletResponse response;

    public void init(HttpServletRequest request, HttpServletResponse response){
        this.request=request;
        this.response=response;
        System.out.println("basecontroller 被调用");
        System.out.println(request.getMethod());
    }
    

    }

     @Aspect
    @Component
    public class aspect {
        @Pointcut("execution(public * com.controller.*.*(..))")
        protected void allPublicMethodCall() {
            // no need to implement this pointcut
        }
    
    
        @Around("allPublicMethodCall()")
        public Object logDefaultApiCallInfo(ProceedingJoinPoint pjp) throws Throwable {
    
    
            Object ControllerCalled = pjp.getTarget();
    
    
            if(ControllerCalled instanceof BaseController){
                Method init=BaseController.class.getDeclaredMethod("init",new Class[]{HttpServletRequest.class, HttpServletResponse.class});
    
                Object[] ags=new Object[]{pjp.getArgs()[0],pjp.getArgs()[1]};
                init.invoke(ControllerCalled,ags);
    
    
            }
    
    
            Object returnValue = pjp.proceed();
    
            return returnValue;
    
        }
    }
    
    
    
    
    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题