SpringBoot初体验

简介

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

理解:从本质上来说,Spring Boot就是Spring的升级版,它做了那些没有它你也会去做的Spring Bean配置。它使用“习惯优于配置”(项目中存在大量的配置,此外还内置了一个习惯性的配置,让你无需手动进行配置)的理念让你的项目快速运行起来。使用Spring Boot很容易创建一个独立运行(运行jar,内嵌Servlet容器)、准生产级别的基于Spring框架的项目,使用Spring Boot你可以不用或者只需要很少的Spring配置。

入门

创建项目

 我们选择的是web项目目录结构如下图

 

查看pom文件,关注如下pom节点

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

spring-boot-starter-parent是一个特殊的starter,它用来提供相关的Maven默认依赖 Spring boot提供的包依赖:m2 epositoryorgspringframeworkootspring-boot-dependencies

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

起步依赖 spring-boot-starter-xx

Spring Boot提供了很多”开箱即用“的依赖模块,都是以spring-boot-starter-xx作为命名的。

快速开始

(1)新建控制器

@RestController
public class HelloController {
    @RequestMapping
    public String index() {
        return "hello spring";
    }

}

(2)运行。。。运行?是的运行

当然spring boot支持三种运行方式,我们直接右键demoApplicatin直接运行,操作简单,方便快捷,发现日志启动成功直接浏览器输入地址(jar包启动java -jar)

2018-01-25 15:00:43.717  INFO 1236 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8077 (http)
2018-01-25 15:00:43.721  INFO 1236 --- [           main] com.dongk.demo.DemoApplication           : Started DemoApplication in 2.172 seconds (JVM running for 2.97)

说明:大家可能关注到我打的端口是8077,默认不是8080吗,是的因为我本地端口被占用了,所以在application.properties中设置了端口

server.port=8077

具体配置设置参考 https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

模板支持

Thymeleaf模板引擎

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。它的功能特性如下:

  • Spring MVC中@Controller中的方法可以直接返回模板名称,接下来Thymeleaf模板引擎会自动进行渲染
  • 模板中的表达式支持Spring表达式语言(Spring EL)
  • 表单支持,并兼容Spring MVC的数据绑定与验证机制
  • 国际化支持

Spring官方也推荐使用Thymeleaf,所以本篇代码整合就使用Thymeleaf来整合。

(1)加入pom依赖便可进行使用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
原文地址:https://www.cnblogs.com/mongo/p/8350964.html