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注解
@Component public 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了!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。