springboot中ServletComponentScan注解的作用

springboot中ServletComponentScan注解的作用

编程文章jaq1232025-07-28 16:57:526A+A-

在SpringBootApplication上使用@ServletComponentScan注解后,
Servlet(控制器)、Filter(过滤器)、Listener(监听器)可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册到Spring容器中,无需其他代码。

@Slf4j
@Order(1)
@WebFilter(filterName="kndFilter", urlPatterns="/*")
public class KndFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    }
@WebServlet(name="TestServlet",urlPatterns="/test")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    		throws ServletException, IOException {
        System.out.println("doGet");
    }
}

ComponentScan

这个注解可以扫描带@Component的类。众所皆知,@RestController和@Configuration和@Service和@Configuration等都有带Component这个注解。所以如果要注入controller和service等,我们可以直接在类上面注解下,并且开启ComponentScan,这样会自动装载并注入这个实例,我们使用的时候可以直接@Autowired使用。ComponentScan做的事情就是告诉Spring从哪里找到bean。

点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21