1、SpringBoot入门-helloWorld

1、SpringBoot入门-helloWorld

  • 什么是 Spring Boot
  • 快速入门
    • Maven 构建项目
    • Idea 构建项目
    • 引入 web 模块

参考: http://www.ityouknow.com/spring-boot.html
这两天在做一个springBoot的单元测试,发现不会写了spingBoot-test的注解,尴尬了,决定把springBoot的东西梳理记录下

什么是 Spring Boot

其实就是简化了spring和别的框架整合的配置(基本上都有默认配置),便于快速快发和使用,“约定优于配置”

快速入门

Maven 构建项目

1、访问 http://start.spring.io/
2、选择构建工具 Maven Project、Java、Spring Boot 版本 2.1.3 以及一些工程基本信息,可参考下图所示:
1、SpringBoot入门-helloWorld_第1张图片
3、点击 Generate Project 下载项目压缩包
4、解压后,使用 Idea 导入项目,File -> New -> Model from Existing Source… -> 选择解压后的文件夹 -> OK,选择 Maven 一路 Next,OK done!
5、如果使用的是 Eclipse,Import -> Existing Maven Projects -> Next -> 选择解压后的文件夹 -> Finsh,OK done!

Idea 构建项目

1、选择 File -> New —> Project… 弹出新建项目的框
2、选择 Spring Initializr,Next 也会出现上述类似的配置界面,Idea 帮我们做了集成
3、填写相关内容后,点击 Next 选择依赖的包再点击 Next,最后确定信息无误点击 Finish。
1、SpringBoot入门-helloWorld_第2张图片
1、SpringBoot入门-helloWorld_第3张图片
1、SpringBoot入门-helloWorld_第4张图片
如上图所示,Spring Boot 的基础结构共三个文件:
src/main/java 程序开发以及主程序入口
src/main/resources 配置文件
src/test/java 测试程序
另外,Spring Boot 建议的目录结果如下:
root package 结构:com.example.myproject
com
± example
± myproject
± Application.java
|
± model
| ± Customer.java
| ± CustomerRepository.java
|
± service
| ± CustomerService.java
|
± controller
| ± CustomerController.java
|
1、Application.java 建议放到根目录下面,主要用于做一些框架配置
2、model 目录主要用于实体与数据访问层(Repository)
3、service 层主要是业务类代码
4、controller 负责页面访问控制
采用默认配置可以省去很多配置,当然也可以根据自己的喜欢来进行更改
最后,启动 Application main 方法,至此一个 Java 项目搭建好了!

引入 web 模块

1、pom.xml中添加支持web的模块:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

pom.xml 文件中默认有两个模块:
spring-boot-starter :核心模块,包括自动配置支持、日志和 YAML,如果引入了 spring-boot-starter-web
web 模块可以去掉此配置,因为 spring-boot-starter-web 自动依赖了 spring-boot-starter。

spring-boot-starter-test :测试模块,包括 JUnit、Hamcrest、Mockito。
2、编写 Controller 内容:

@RestController
public class HelloWorldController {
     
    @RequestMapping("/hello")
    public String index() {
     
        return "Hello World";
    }
}

@RestController 的意思就是 Controller 里面的方法都以 json 格式输出,不用再写什么 jackjson 配置的了!
3、启动主程序,打开浏览器访问 http://localhost:8080/hello,就可以看到效果了,有木有很简单!

你可能感兴趣的:(springboot,java)