Spring-boot通过maven创建一个项目

转载自:Spring-boot通过maven创建一个项目

1、打开idea选择创建工程

Spring-boot通过maven创建一个项目

回到顶部

2、创建maven工程,同时选择jdk1.8

注意:不需要勾选其他选项

Spring-boot通过maven创建一个项目

回到顶部

3、填写项目名称

Spring-boot通过maven创建一个项目

回到顶部

4、创建好maven项目后,在pom.xml文件中导入Spring Boot需要的jar包

Spring-boot通过maven创建一个项目

 1 <!-- 指定Spring Boot的版本 2.0.4.RELEASE -->
 2 <parent>
 3     <groupId>org.springframework.boot</groupId>
 4     <artifactId>spring-boot-starter-parent</artifactId>
 5     <version>2.0.4.RELEASE</version>
 6 </parent>
 7 
 8 <dependencies>
 9    <!-- 导入Spirng Boot  web 所需的jar包 -->
10     <dependency>
11         <groupId>org.springframework.boot</groupId>
12         <artifactId>spring-boot-starter-web</artifactId>
13     </dependency>
14 </dependencies>

Spring-boot通过maven创建一个项目

回到顶部

5、创建一个主程序类,用于启动Spring Boot应用

注意:必须注解@SpringBootApplication和一个run方法

 Spring-boot通过maven创建一个项目

Spring-boot通过maven创建一个项目

 1 /**
 2  * @SpringBootApplication:标注一个主程序类,用来标明这是一个Spring Boot应用
 3  */
 4 @SpringBootApplication
 5 public class SpringBootApplicationMain {
 6     // Spring应用启动起来
 7     public static void main(String[] args) {
 8         SpringApplication.run(SpringBootApplicationMain.class, args);
 9     }
10 }

Spring-boot通过maven创建一个项目

回到顶部

6、编写相关的Controller类

注意:1.相关的类必须和主程序类同一个包下,或者为主程序包的子包下

           2. @RestController相当与 @Controller + @ResponseBody 一起使用,表示整个Controller的方法返回值都是json或json对象

Spring-boot通过maven创建一个项目

Spring-boot通过maven创建一个项目

1 @Controller
2 @ResponseBody
3 // @RestController
4 public class HelloController {
5         @RequestMapping("/hello")
6         public String hello(){
7             return "HelloController中的hello方法";
8         }
9 }

Spring-boot通过maven创建一个项目

观察源码@RestController实际上就是 @Controller + @ResponseBody

Spring-boot通过maven创建一个项目

回到顶部

7、运行main方法,在浏览器中访问得到结果

 Spring-boot通过maven创建一个项目

回到顶部

8. Spring Boot 可以简化部署,pom.xml导入一个打包插件

Spring-boot通过maven创建一个项目

1 <!-- 这个插件,可以将应用打包成一个可执行的jar包;-->
2 <build>
3     <plugins>
4         <plugin>
5             <groupId>org.springframework.boot</groupId>
6             <artifactId>spring-boot-maven-plugin</artifactId>
7         </plugin>
8     </plugins>
9 </build>

Spring-boot通过maven创建一个项目

回到顶部

9、执行打包工程成jar包

Spring-boot通过maven创建一个项目

Spring-boot通过maven创建一个项目

回到顶部

10、运行 jar 包

注意:是在jar 包目录下运行 java –jar

 Spring-boot通过maven创建一个项目

 

回到顶部

注意事项:

1. 选择自动导入(右下角),没由选中,请看下一条

Spring-boot通过maven创建一个项目

2. 如果没有选中,可以手动自己更新Maven项目(右上角)

Spring-boot通过maven创建一个项目

3.出现下面错误,上面由提过,Controller存放的路径是需要注意的。

 Spring-boot通过maven创建一个项目