spring boot --- 注解 @Bean 和@Component
1.前言
@Bean是给方法注册bean
@Component是给不好归类的类注册bean
2.可以达到一样的效果
(1)@Component 直接注册即可
完整源码
package com.example.demomycenzuul.myFilter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import org.apache.commons.lang.StringUtils; import org.slf4j.LoggerFactory; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.logging.Logger; @Component public class AccessFilter extends ZuulFilter { @Override public String filterType() { return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { System.out.println("进入zuul拦截"); //获取上下文 RequestContext ctx = RequestContext.getCurrentContext(); //获取Request HttpServletRequest request = ctx.getRequest(); //获取请求参数accessToken String accessToken = request.getParameter("accessToken"); //使用String工具类 if (StringUtils.isBlank(accessToken)) { ctx.setSendZuulResponse(false); //进行拦截 ctx.setResponseStatusCode(401); try { ctx.getResponse().getWriter().write("accessToken is empty,-------401"); } catch (Exception e) { } return null; } return null; } }
(2)@bean则不需要在类加注解
但是,需要去启动类new这个类
本文来自博客园,作者:岑惜,转载请注明原文链接:https://www.cnblogs.com/c2g5201314/p/12892455.html
响应开源精神相互学习,内容良币驱除劣币