spring boot的ComponentScan和ServletComponentScan注解
阅读原文时间:2021年05月10日阅读:1

这个注解可以扫描带@Component的类。众所皆知,@RestController和@Configuration和@Service和@Configuration等都有带Component这个注解。所以如果要注入controller和service等,我们可以直接在类上面注解下,并且开启ComponentScan,这样会自动装载并注入这个实例,我们使用的时候可以直接@Autowired使用,下面以controller为栗子:

a:首先在spring boot启动入口开启自动扫描Component的注解(在类上面使用@ComponentScan),这个注解可以配置扫描的路径,我这里配置com.xx,也就是我把controller都放这里,系统会自动注入

由于@ComponentScan其实在SpringBootApplication这里已经有了,我们可以直接用scanBasePackages扫描的路径。即不用ComponentScan这个注解了,取而代之的是用SpringBootApplication

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootApplication(scanBasePackages = "com.xx")
@ServletComponentScan(basePackages="com.example.demo")public class DemoApplication {

public static void main(String\[\] args) {  
    SpringApplication.run(DemoApplication.class, args);  
}

}

b:controller层编写

package com.xx;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author zhujianming
* @date 2021-05-10 10:24
*/
@RestController
public class PPController {
@RequestMapping("/testp")
public String hello(){
return"Hello world!";
}

}

这样直接访问localhost:8080/testp就会返回json了

上面一步在spring boot中启动类加了@ServletComponentScan(basePackages="com.example.demo"),所以扫描路径是com.example.demo,我们下一步在com.example.demo编写个Servlet作为案例

编写@WebServlet

package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@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");  
}  

}

这样直接访问/test就会在控制台输出doGet,当然这个注解也会扫描Filter等控件,有空可以去试试

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器