SprintBoot的@ComponentScan“踩坑”

主要的话说在前面:在启动日志中没有看到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":

猜你喜欢

转载自www.cnblogs.com/pedlar/p/9787060.html
今日推荐