spring boot的ComponentScan和ServletComponentScan注解


ComponentScan

這個注解可以掃描帶@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了

ServletComponentScan

上面一步在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等控件,有空可以去試試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM