zoukankan      html  css  js  c++  java
  • 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;
        }
    
    }
    View Code

     (2)@bean则不需要在类加注解

     但是,需要去启动类new这个类

  • 相关阅读:
    制作Autorun的CD
    Sybase ASE MDA tables 装不上怎么办?
    对于TStringList.Find函数,我有话要说
    HH.exe CHM Operator Command.
    Delphi 7的一些常用的快捷键
    Explain Plan
    在Delphi中的Log
    subst windows下实用的磁盘映射工具
    Excel 2007 如何冻结多行&多列
    LinqToDataTable[转]
  • 原文地址:https://www.cnblogs.com/c2g5201314/p/12892455.html
Copyright © 2011-2022 走看看