springboot学习笔记:2.搭建你的第一个springboot应用

 springboot

1.开发环境

(推荐):jdk1.8+Maven(3.2+)+Intellij IDEA+windows10;

说明:

jdk:springboot官方说的很明确,到目前版本的springboot(1.5.9),官方指定要求jdk1.8以上;

依赖包管理:可以通过拷贝jar文件的方式管理依赖,但官方也推荐使用Apache Maven 3.2或更高版本等构件工具;

开发工具:个人推荐使用IDEA,功能很强大,使用流畅度和方便性较好;


2.开始我们的第一个springboot项目

本节目标:构造第一个springboot入门web项目,通过三种方式运行启动;并通过浏览器得到服务器反馈结果;

步骤:

2.1.验证本机的jdk版本和mvn版本

确保在jdk1.8和maven3.2+;

2.2.创建项目(使用springboot官方推荐的创建方式——spring initializr):

进入https://start.spring.io/,选择要使用的springboot版本号,这里使用1.5.9,填写好项目组信息,在Search for dependencies中搜索web并选中;

选择生成项目后自动下载chapter01.zip;解压chapter01.zip后,使用IDEA打开chapter01项目文件夹;

此外,还可以在IDEA中File-new-Project,选择Spring Initializr,在IDEA中创建springboot项目;

(注意:此处如果你的项目报错,请确保该项目的maven配置正确;IDEA的话打开,正确指定好使用的maven是3.2以上版本即可:

)

项目正常打开后的目录结构如下:

Chapter01Application.java  内部包含main函数,是springboot项目的启动类;

Chapter01ApplicationTests.java  测试类

pom.xml  依赖管理文件

application.properties  配置文件,初次生成的时候是空的,以后可以在里面填写配置项;

 

有的同学到这里有些懵,以往java web项目不是有个WebRoot文件夹吗,这里我明明配置的就是web项目,为什么会是这么个目录结构呢?

这里其实就是springboot提倡的习惯,以后开发springboot,要习惯使用模板,摒弃jsp的前端方案(如果你执意要使用jsp的话也是可以的,我们后文会介绍);现在我们项目组开发,基本全是freemarker,而且基本上全部都是请求rest 接口,这样前后端完全分离;避免了在jsp中写java代码的陋习(记得以前做过一个H5支付页面,用jsp写的,后来项目升级,前端用vue.js,结果后台需要重新写n多接口);以后项目想更换前端方案也不会是坑;所以要接受并学习使用模板;要彻底执行前后端分离的思想;

以前使用jsp时,你会把jsp放在WEB-INF下面;以后使用模板,你需要把模板全放到例如resources-templates下面去;

sprinboot到底使用什么模板,因人而异;我个人喜欢freemarker;

以freemarker为例,模板.ftl文件会被放到resources.templates中,其他静态资源文件会被放到resources-static中,这块日后再婊;

2.3项目详解

2.3.1详解pom.xml

我们把目光先集中在maven的pom.xml中,看看官方生成的这个依赖结构:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zjt</groupId>
    <artifactId>chapter01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>chapter01</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

 

 是不是看上去很简单,其实里面大有玄机;

首先,注意打包文件格式是jar文件,这是因为,sprinboot使用mvn插件可以打包成可执行的内嵌web容器的jar,这对于发布微服务是很方便的;如果想打成war包和其他项目一起集成在tomcat中,也是可以的,这个日后再表;

构建项目:

 方法1:父依赖(spring initializr默认构建方式):

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

此处,我们发现springboot官方默认使用父依赖的方式来构件springboot项目。ctrl+左键点击跟踪spring-boot-starter-parent,会发现其实她继承了spring-boot-dependencies;包括日后我们常用的配置文件的过滤等

总结起来,可以说spring-boot-starter-parent,有如下特性:

默认编译级别为Java 1.8
源码编码为UTF-8
一个依赖管理节点,允许你省略普通依赖的 <version>  标签,继承自 spring-boot-dependencies  POM。
合适的资源过滤
合适的插件配置(exec插件,surefire,Git commit ID,shade)
针对 application.properties  和 application.yml  的资源过滤

 只要指定了父依赖的version,那么其相关的其他自动依赖均无需再指定版本号,springboot已经自动管理好了最佳的依赖配置,如图:

这也是springboot的方便之处;

除非你手动覆盖自己的项目中的属性,来达到修改某个依赖的版本号的目的;

方法2:使用import来引入spring-boot-dependencies

如果不想使用父依赖的方式,可以直接通过使用一个 scope=import  的依赖来构建:

<dependencyManagement>
        <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.0.0.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Starter POMS :

下面我们看一下pom.xml中的依赖模块,发现有一些很有特色的spring-boot-starter-*,官方学名叫starter poms;

springboot使用各种starter poms来实现组件的热插拔;每一个starter pom就是一个可以包含到应用中的一个方便的依赖关系描述符集合;可以获取所有Spring及相关技术的一站式服务,而不需要翻阅示例代码,拷贝粘贴大量的依赖描述符。

例如,如果你想使用Spring和JPA进行数据库访问,只需要在你的项目中包含 spring-boot-starter-data-jpa 依赖,然后你就可以开始了。

下面的应用程序starters是Spring Boot在 org.springframework.boot  组下提供的,我们可以方便地查找你的项目需要的其他组件的starter,直接添加即可自动加载依赖:

Table 13.1. Spring Boot application starters

NameDescriptionPom

spring-boot-starter

Core starter, including auto-configuration support, logging and YAML

核心Spring Boot starter,包括自动配置支持,日志和YAML

Pom

spring-boot-starter-activemq

Starter for JMS messaging using Apache ActiveMQ

Pom

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ

对"高级消息队列协议"的支持,通过 spring-rabbit  实现

Pom

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ

对面向切面编程的支持,包括 spring-aop  和AspectJ

Pom

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

Pom

spring-boot-starter-batch

Starter for using Spring Batch

对Spring Batch的支持,包括HSQLDB数据库

Pom

spring-boot-starter-cache

Starter for using Spring Framework’s caching support

Pom

spring-boot-starter-cloud-connectors

Starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku

对Spring Cloud Connectors的支持,简化在云平台下(例如,Cloud Foundry 和Heroku)服务的连接

Pom

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

Pom

spring-boot-starter-data-cassandra-reactive

Starter for using Cassandra distributed database and Spring Data Cassandra Reactive

Pom

spring-boot-starter-data-couchbase

Starter for using Couchbase document-oriented database and Spring Data Couchbase

Pom

spring-boot-starter-data-couchbase-reactive

Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive

Pom

spring-boot-starter-data-elasticsearch

Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch

对Elasticsearch搜索和分析引擎的支持,包括 spring-data-elasticsearch

Pom

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate

对"Java持久化API"的支持,包括 spring-data-jpa  , spring-orm  和Hibernate

Pom

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

Pom

spring-boot-starter-data-mongodb

Starter for using MongoDB document-oriented database and Spring Data MongoDB

对MongoDB NOSQL数据库的支持,包括 spring-data-mongodb

Pom

spring-boot-starter-data-mongodb-reactive

Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive

Pom

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

Pom

spring-boot-starter-data-redis

Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client

Pom

spring-boot-starter-data-redis-reactive

Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client

Pom

spring-boot-starter-data-rest

Starter for exposing Spring Data repositories over REST using Spring Data REST

对通过REST暴露Spring Data仓库的支持,通过 spring-data-rest-webmvc  实现

Pom

spring-boot-starter-data-solr

Starter for using the Apache Solr search platform with Spring Data Solr

对Apache Solr搜索平台的支持,包括 spring-data-solr

Pom

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views

对FreeMarker模板引擎的支持

Pom

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

对Groovy模板引擎的支持

Pom

spring-boot-starter-hateoas

Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS

对基于HATEOAS的RESTful服务的支持,通过 spring-hateoas  实现

Pom

spring-boot-starter-integration

Starter for using Spring Integration

对普通 spring-integration  模块的支持

Pom

spring-boot-starter-jdbc

Starter for using JDBC with the Tomcat JDBC connection pool

对JDBC数据库的支持

Pom

spring-boot-starter-jersey

Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web

对Jersey RESTful Web服务框架的支持

Pom

spring-boot-starter-jooq

Starter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc

Pom

spring-boot-starter-json

Starter for reading and writing json

Pom

spring-boot-starter-jta-atomikos

Starter for JTA transactions using Atomikos

对JTA分布式事务的支持,通过Atomikos实现

Pom

spring-boot-starter-jta-bitronix

Starter for JTA transactions using Bitronix

对JTA分布式事务的支持,通过Bitronix实现

Pom

spring-boot-starter-jta-narayana

Spring Boot Narayana JTA Starter

Pom

spring-boot-starter-mail

Starter for using Java Mail and Spring Framework’s email sending support

对 javax.mail  的支持

Pom

spring-boot-starter-mustache

Starter for building web applications using Mustache views

对Mustache模板引擎的支持

Pom

spring-boot-starter-quartz

Spring Boot Quartz Starter

Pom

spring-boot-starter-security

Starter for using Spring Security

对 spring-security  的支持

Pom

spring-boot-starter-test

Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito

Pom

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views

对Thymeleaf模板引擎的支持,包括和Spring的集成

Pom

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator

Pom

spring-boot-starter-web

Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container

对全栈web开发的支持,包括Tomcat和 spring-webmvc

Pom

spring-boot-starter-web-services

Starter for using Spring Web Services

Pom

spring-boot-starter-webflux

Starter for building WebFlux applications using Spring Framework’s Reactive Web support

Pom

spring-boot-starter-websocket

Starter for building WebSocket applications using Spring Framework’s WebSocket support

对WebSocket开发的支持

Pom

除了应用程序的starters,下面的starters可以用于添加生产准备的特性:

Table 13.2. Spring Boot production starters

NameDescriptionPom

spring-boot-starter-actuator

Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application

添加生产准备特性,比如指标和监控

Pom

最后,Spring Boot包含一些可用于排除或交换具体技术方面的starters。

Table 13.3. Spring Boot technical starters

NameDescriptionPom

spring-boot-starter-jetty

Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat

导入Jetty HTTP引擎(作为Tomcat的替代)

Pom

spring-boot-starter-log4j2

Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging

对Log4J日志系统的支持

Pom

spring-boot-starter-logging

Starter for logging using Logback. Default logging starter

导入Spring Boot的默认日志系统(Logback)

Pom

spring-boot-starter-reactor-netty

Starter for using Reactor Netty as the embedded reactive HTTP server.

Pom

spring-boot-starter-tomcat

Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web

导入Spring Boot的默认HTTP引擎(Tomcat)

Pom

spring-boot-starter-undertow

Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat

导入Undertow HTTP引擎(作为Tomcat的替代)

Pom

 使用maven插件用来打包springboot项目

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
</build>

 

 

 2.3.2代码详解:

项目启动类(Chapter01Application.java):

package com.zjt.chapter01;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Chapter01Application {

    public static void main(String[] args) {
        SpringApplication.run(Chapter01Application.class, args);
    }
}

 

 上述Chapter01Application.java为springboot的main启动类;

这里我们开始学习到了springboot启动类中的最重要的一个注解:@SpringBootApplication

注意:

1.项目启动类,根据官方建议,一定要位于非 default package下;也就是说这个启动类一定要含有package的声明;建议使用反转域名;如com.zjt.learn;

2.官方建议,main应用类要放在其他类上面的根包(root package)中;

3.@SpringBootApplication该注解在基于上述1和2两点下,才可以使用(习惯优于配置);

由于该注解相当于:

@SpringBootConfiguration

@EnableAutoConfiguration

@ComponentScan

_______________华丽的小分割__________________

@SpringBootConfiguration:说明当前类是一个配置类,就像xml配置文件,而现在是用java配置文件,效果是一样的,它会被@ComponentScan扫描到。

@EnableAutoConfiguration(开启自动配置,springboot的灵魂所在)注解通常都放到main所在类的上面,当main所在类位于root package的时候,这样@EnableAutoConfiguration可以从逐层的往下搜索各个加注解的类,例如,你正在编写一个JPA程序(如果你的pom里进行了配置的话),spring会自动去搜索加了@Entity注解的类,并进行调用;

 @ComponentScan:用注解配置实现自动扫描,默认会扫描当前包和所有子包,和xml配置自动扫描效果一样;

___________________________________________

所以我们的springboot很贴心的为我们准备了Springboot 提供了统一的注解@SpringBootApplication来替代以上三个注解,简化程序的配置;

2.3.3.最后我们自己添加controller包,添加一个TestController.java,接受rest请求:

package com.zjt.chapter01.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RequestMapping("/hello")
    public String Hello(){
        return "hello world";
    }
}

 2.4.启动项目

 2.4.1使用main启动类启动:

 

看到这样就证明已经顺利启动了;

 

 

 

 2.4.2使用mvn spring-boot:run”在命令行启动;

2.4.3使用mvn package打成可执行jar;使用java -jar启动;

mvn clean ;mvn build; mvn package;

打包后,命令行启动:

 

 


 

OK,今天的入门我们就一起做到这里;后续会同大家共同探讨很多springboot的实用教程和案例;文章中有什么问题或者想法欢迎老铁们吐槽和我沟通;我会及时纠正错误,改进教程的品质;

做程序需要静心,扎扎实实做技术;不忘初心,脚踏实地,就酱。

 

 

 

posted on 2018-01-17 00:30  zhaojiatao  阅读(4182)  评论(0编辑  收藏  举报

导航