搭建一个spring boot 项目的雏形很简单,见一个空的项目外壳(file-new project(不勾选模版)-填写groupId和artifactId 一直next完成),然后在pom加上以下代码:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
然后写一个@SpringBootApplication 的启动类,就完成雏形了。
但是springboot的项目结构有注意的地方:如图,有说明(application启动类要和controller父目录同级或者和controller放在同一个包下面,否则默认扫描会扫描不到controller。这个时候要配置@ComponentScan才能扫描到)。图的
如图,默认扫描不会扫描到,需要这样写:
@SpringBootApplication
@ComponentScan(basePackages="com.zhihao.controller")
public class DemoApplication {
public static void main(String[] args){
SpringApplication.run(DemoApplication.class,args);
}
}
如果需要访问springboots的html,需要pom增加依赖,增加之后,返回字符串会直接到resources/templates/ 下面找页面:
<!--加了这个spring boot 的controller 可以直接跳转到resources/templates/*.html-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
写一个测试的controller:
@Controller
public class HelloController {
@RequestMapping("/index")
public String index(){
System.out.println("---------success----------");
return "welcome";//到resources/templates/去找页面
}
@RequestMapping("/data")
@ResponseBody
public String data(){
System.out.println("---------success----------");
return "somData";//@ResponseBody的作用下,返回字符串“somDate”
}
}
启动application注解类,即可启动这个springboot项目,输入controller的对应路径访问。