千家信息网

springboot中@component注解如何使用

发表于:2025-01-19 作者:千家信息网编辑
千家信息网最后更新 2025年01月19日,这篇文章主要介绍"springboot中@component注解如何使用",在日常操作中,相信很多人在springboot中@component注解如何使用问题上存在疑惑,小编查阅了各式资料,整理出简
千家信息网最后更新 2025年01月19日springboot中@component注解如何使用

这篇文章主要介绍"springboot中@component注解如何使用",在日常操作中,相信很多人在springboot中@component注解如何使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"springboot中@component注解如何使用"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

@component注解的使用

配置响应头的内容。

方式一

直接在拦截器里配置响应头内容。

/** * 拦截器--用户身份确认。 */public class RestInterceptor implements HandlerInterceptor {        private static final Logger log = LoggerFactory.getLogger(RestInterceptor.class);    private static final String tokenHeader = "Authorization";     /**          *  返回值:true表示继续流程(如调用下一个拦截器或处理器);false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;      */    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        log.info("拦截请求");        //响应头        response.setHeader("Access-Control-Allow-Origin", "*");        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,authorization");        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");                if(request.getMethod().equals("OPTIONS")){            response.setStatus(204);            return true;        }                log.info("调用接口:method=" +request.getParameter("method")+",params="+JSON.toJSONString(request.getParameterMap()));        //        HandlerMethod handlerMethod = (HandlerMethod)handler;//        RequestAuth requestAuth = handlerMethod.getMethodAnnotation(RequestAuth.class);//        if(requestAuth!=null && requestAuth.auth()==false){ //非验证API //            return true;//跳过验证//        }        //验证//        String token = request.getHeader(tokenHeader);//        if(token == null || token.equals("")) {//            log.info("没有找到token");//            throw new BusinessException(ResMsg.CODE_TOKEN_NOTFOUND, "没有找到token");//        } else {//            JWSObject jwsObject = JWSObject.parse(token);//            Payload payload = jwsObject.getPayload();//            JSONObject obj = payload.toJSONObject();            //            String roleNames = String.valueOf(obj.get("roleNames"));//            Authentication auth = new Authentication();//            if(obj.containsKey("platformId")) {//                Long platformId = Long.valueOf(String.valueOf(obj.get("platformId")));//                auth.setPlatformId(platformId);//            }//            if(obj.containsKey("userid")) {//                Long userId = Long.valueOf(String.valueOf(obj.get("userid")));//                auth.setUserId(userId);//            }//            if(obj.containsKey("orgId")) {//                Long orgId = Long.valueOf(String.valueOf(obj.get("orgId")));//                auth.setOrgId(orgId);//            }//            if(obj.containsKey("orgid")) {//为兼容老版本的接口//                String orgid = String.valueOf(obj.get("orgid"));//                orgid = orgid.replace(",", "");//                Long orgId = Long.valueOf(orgid);//                auth.setOrgId(orgId);//            }//            auth.setRoleNames(roleNames);//            SecurityContext.setContext(auth);//            JwtUtil.verify(jwsObject);//        }        return true;    }     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,            ModelAndView modelAndView) throws Exception {        //log.info("处理中");    }     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)            throws Exception {        if(ex != null) {            log.error("接口处理异常:"+ex);            throw ex;        }    }}

方式二

使用@component注解,将普通JavaBean实例化到spring容器中。

public class RestInterceptor implements HandlerInterceptor {        private static final Logger log = LoggerFactory.getLogger(RestInterceptor.class);    private static final String tokenHeader = "Authorization";     /**          * 返回值:true表示继续流程(如调用下一个拦截器或处理器);false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;      */    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        log.info("拦截请求");                  if(request.getMethod().equals("OPTIONS")){            response.setStatus(204);            return true;        }                log.info("调用接口:method=" +request.getParameter("method")+",params="+JSON.toJSONString(request.getParameterMap()));                 return true;    }     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,            ModelAndView modelAndView) throws Exception {        //log.info("处理中");    }     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)            throws Exception {        if(ex != null) {            log.error("接口处理异常:"+ex);            throw ex;        }    }}

定义 SimpleCORSFilter.java 类, 使用@component注解

@Componentpublic class SimpleCORSFilter implements Filter {    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {        HttpServletResponse response = (HttpServletResponse) res;        response.setHeader("Access-Control-Allow-Origin", "*");        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");        response.setHeader("Access-Control-Max-Age", "3600");        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,authorization");        chain.doFilter(req, res);    }     public void init(FilterConfig filterConfig) {}     public void destroy() {}    }

两种方式都可以完成响应。

@component注解有什么作用

用一句话概括

被@Component注解标识的类,会被纳入Spring容器中统一管理,好处是什么?一句话概括:你不用自己new了!

到此,关于"springboot中@component注解如何使用"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0