建立spring boot的方式有很是多,今天咱们使用maven来进行建立spring boot项目,由于maven使用的很是普遍,也很好用,不少IDE也都支持maven。java
1 建立maven项目web
1.1 使用eclipse建立maven项目spring
(1)File —>New —> Project...浏览器
(2)选中Maven Project ,点击下一步app
(3)默认设置 点击下一步eclipse
(4)继续点击 下一步maven
(5)以下图设置Group Id(组织Id/项目包名) 和Artifact Id(项目名称或者模块名称),而后点击Finish。到此咱们就完成了用eclipse建立maven项目。spring-boot
1.2 使用IntelliJ IDEA 建立maven项目this
(1)File —> New —>Project编码
(2)选中maven点击下一步
(3) 以下图设置Group Id(组织Id/项目包名) 和Artifact Id(项目名称或者模块名称),而后点击下一步。
(4)IDEA会根据上一步的设置默认project name和project location,若是不须要变动则点击Finish。
(5)到此为止,咱们就完成了使用IntelliJ IDEA建立maven项目。
2 项目构建
2.1 添加maven依赖
(1)在pom文件中添加如下依赖:
1 <parent> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-parent</artifactId> 4 <version>2.0.4.RELEASE</version> 5 </parent>
spring-boot-starter-parent 是一个特殊的starter,主要是给项目提供一些默认配置:
(2)咱们如今要开发一个web项目,则须要引入一个web的starter的依赖:
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-web</artifactId> 5 </dependency> 6 </dependencies>
2.2 编写启动类
(1)在maven工程的java目录下建立包名为com.sunshine的包
(2)在上面的包下面建立一个 Application的类,并给Application类添加 @EnableAutoConfiguration 注解,以下所示:
1 @EnableAutoConfiguration 2 public class Application { 3 4 public static void main(String[] args){ 5 SpringApplication.run(Application.class,args); 6 } 7 }
(3)建立spring MVC的controller,咱们如今com.sunshine包下面建立包名为 controller 的包,在该包下面建立名为DemoController的controller类。以下所示:
1 @RestController 2 public class DemoController { 3 4 @GetMapping("/demo") 5 public String demo(){ 6 return "Hello,this is a spring boot demo."; 7 } 8 }
(4)由于咱们建立的一个DemoController类,在该类下建立了一个“/demo”接口,咱们须要把DemoController注册到spring MVC容器中,则须要在启动类Application上面添加注解 @ComponentScan进行扫描包扫描,代码以下:
1 @EnableAutoConfiguration 2 @ComponentScan 3 public class Application { 4 5 public static void main(String[] args){ 6 SpringApplication.run(Application.class,args); 7 } 8 }
在这里须要注意的是 @ComponentScan注解只能扫描启动类所在的包下面的类文件,因此一般咱们都把启动类放在根包路径,好比咱们如今的根包路径就是com.sunshine。
咱们也可使用 @SpringBootApplication注解代替 @EnableAutoConfiguration和@ComponentScan两个注解,以下所示:
1 @SpringBootApplication 2 public class Application { 3 4 public static void main(String[] args){ 5 SpringApplication.run(Application.class,args); 6 } 7 }
2.3 启动项目
(1)在启动类中直接运行main方法便可,以下图所示就是启动成功了:
(2)在浏览器中输入http://localhost:8080/demo进行访问咱们刚刚编写的"/demo"接口,效果以下图所示:
3 总结
到此为止,已经完成建立spring boot项目。
若是有什么问题欢迎留言指出,若是有什么疑问欢迎留言评论。