springboot多模塊controller訪問的問題


參考 https://blog.csdn.net/qq_25091649/article/details/88429512

 

情況一:在主類直接寫controller接口,能夠訪問到

@SpringBootApplication
@RestController
public class DemoApplication {
	@RequestMapping("/index")
    public String index() {
      
        return "this is index!";
    }


	public static void main(String[] args) {
		//SpringApplication.run(DemoApplication.class, args);
		SpringApplication application = new SpringApplication(DemoApplication.class);
		application.setBannerMode(Mode.OFF);//關閉banner
		application.run(args);
	}

}


情況二:controller類單獨寫,且controller所在目錄低於主類目錄,此時也可以訪問到

  

情況三:controller類單獨寫,且controller所在目錄不在住類目錄下,此時需要添加注解ComponentScan,里面寫入要掃描的包

 

@ComponentScan(basePackages = {"com.xiao","com.example"})
@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		//SpringApplication.run(DemoApplication.class, args);
		SpringApplication application = new SpringApplication(DemoApplication.class);
		application.setBannerMode(Mode.OFF);//關閉banner
		application.run(args);
	}

}

1、當啟動類和controller在同一類中時,需要在該類上添加注解@Controller;

2、當啟動類和controller分開時,啟動目錄高於controller目錄,啟動類上只有注解@SpringBootApplication;

3、當啟動類和controller分開時,如果啟動類在某個包下,需要在啟動類中增加注解@ComponentScan,配置需要掃描的包名;

 

補充說明:對外的只有主類所在的模塊,所以需要把其它模塊添加到住類所在模塊


免責聲明!

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



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