码迷,mamicode.com
首页 > 其他好文 > 详细

SprintBoot的@ComponentScan“踩坑”

时间:2018-10-14 19:00:12      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:server   map   import   stc   tap   prope   一个   oid   java   

主要的话说在前面:在启动日志中没有看到Controller对应的URL被映射,那么请检查你的Controller是否被Spring管理了。此次踩坑就是忘了SpringBoot在没配置@ComponentScan的情况下,默认只扫描和主类处于同包下的Class。

一个很简单的Spring Boot的Hello World,主要是根据请求返回一个字符串。如下是项目结构:

技术分享图片

  主类Application.java:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

  Controller类HelloController:

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

@RestController
public class HelloController {
	@RequestMapping(value="/hello", method = RequestMethod.GET)
	public String hello() {
		 return "Hello, Spring Boot";
	}
}

  配置文件application.properties:

server.port=8082
server.servlet.context-path=/springboot  

  启动日志中没有看到请求"/hello"被映射:

技术分享图片

 

因为Application和HelloController没有在同一个包下,且在Application中没有加上@ComponentScan指定扫描路径,所以HelloController并没有被纳入Spring管理,那么在启动日志中肯定就见不到HelloController的URL的Mapping。

   解决办法:

  1. 将Application和HelloController放到同一个包下

  2.在Application商加上@ComponentScan,指定需要扫描的路径。这里我们将采用这种方法。

  加上@ComponentScan的Application:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.andywooh.springboot")
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

  启动日志终于看到"/hello":

技术分享图片

 

SprintBoot的@ComponentScan“踩坑”

标签:server   map   import   stc   tap   prope   一个   oid   java   

原文地址:https://www.cnblogs.com/pedlar/p/9787060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!