10月23, 2018

Spring Boot(一) 快速开始

Spring Boot 快速开始

一.什么是Spring Boot

-w1114 这是Spring官方首页https://spring.io/的截图,图和下面的文字说明,已经很形象的说明了Spring boot现在的地位和作用.

Spring Boot 是所有基于 Spring 开发的项目的起点。Spring Boot 的设计是为了让你尽可能快的跑起来

如果你打算学习Spring Boot,并不用紧张,他其实并不是一门新的技术,对于入门者来说,你可以这么简单的理解,他其实就是一个帮你自动配置了很多以前需要你去手动配置的Spring Bean,让你的项目快速的搭建起来,尽快的干正事,而不是在项目的一开始就要去头疼项目搭建的问题

回顾一下,我们写代码之前要干些啥事? 1). 配置web.xml 2). 配置Maven pom.xml 3). 配置spring,spring MVC,配置相关的Bean 4). 配置tomcat

这是之前,我们写web项目,就是想在页面看到一个简单的Hello world反馈,至少都要做这些事情.那现在我们就使用Spring Boot,看看有多快.

二.快速开始-搭建一个Web项目基本框架

  1. 访问: https://start.spring.io/,这个页面可以帮我们直接生成一个Spring Boot项目的框架
  2. 接下来其实就是通过这个页面帮我们创建一个Spring Boot的基本工程,工程可以选择以Maven进行构建,Spring Boot的版本我这里选择的是1.5.7,GroupArtifact填入你自己的就好,由于我们要创建一个Web工程,所以这里的dependencies,我选择了Web.至于这里的选择是什么意思,我们后面再详细描述 -w1188
  1. 点击Generate Project下载Spring Boot基本项目压缩包
  2. 使用eclipse导入工程,注意,这个工程是一个Maven工程 eclispe -> Import -> Other -> Maven -> Existing Maven Projects, ok,选择之前解压缩的文件,导入就行了 导入之后,文件的基本结构就是下面这个样子 -w255

  3. 基本框架都有了,可以看到项目自动给我们生成了一个QuickApplication.java的文件,这个java文件中是有main方法的,它就是整个SpringBoot的启动文件,运行这个文件 -w956 在Console窗口中就有了这个结果. 启动这个文件,其实就已经帮我们启动的Tomcat服务器,因为我们在导入Web依赖的时候,这个Web依赖中就已经嵌入了Tomcat,那现在启动浏览器就已经可以在127.0.0.1:8080端口上访问了,不过现在访问是下面这样的结果 -w799

  4. 很显然,服务器是有了,只是我们现在还没有任何页面,那现在就在程序中添加一个Controller给页面直接反馈一些消息. -w881 里面有一些注解,如果你了解SpringMVC的话,就知道具体的意义了,这些注解的含义我们也在后面再详细说明,那么现在重新启动工程,再访问127.0.0.1:8080/hello -w581 正确得到了HelloController的反馈

至少现在,我们工程的基本框架已经就都有了

三.导入工程可能存在的问题

当然,如果没有问题的话,你执行的过程应该和我一样的,什么叫没有问题呢?很多人应该会遇到下面的这个问题 -w894 导入工程之后,直接报出感叹号,而且运行QuickApplication.java,会报出找不到主类的错误,要解决这个问题很简单,不要让程序报感叹号就好了. -w1030 这样,就可以运行QuickApplication.java了,但是原因是什么呢?其实注意看工程的包引用,就能看到原因: -w1015 很明显,有很多包Maven都能导入进来,这是由于使用了eclipse自带默认的Maven所导致的,所以,最好的解决办法就是eclipse配置自己的Maven,因为自己配置的Maven我们一般都会重新修改源,以及jar包路径,就不会出现使用默认源导致包导入不完全的情况了 -w895

四.Spring Boot工程的最佳实践

其实从上面的代码和错误,也就能看出来,首要,你要学习Spring Boot,至少需要学习了解过下面的几个知识点

  1. maven
  2. Spring MVC

如果你还不清楚怎么利用Maven构建项目,Maven的配置,Spring MVC的基本理论,运行过程和注解,还有RESTful风格相关API等等,那么直接上手学习Spring Boot还是很有难度的. 除了这两个前置知识点,为了让我们的Spring Boot程序快速的搭建起来,而且不出现让我们初学者莫名其妙的错误,还建议大家在导入Spring Boot工程之前,做一下下面的前置准备

  1. JDK1.8
  2. 自定义的Maven的配置
  3. Eclipse的配置

至少做好上面的几个配置,才能保证你的Spring Boot工程导入的时候不报错误.

首先是Maven自身的settings.xml的配置

配置本地仓库

<!--自定义本地仓库路径-->
<localRepository>你的本地路径地址比如E:\m2\jar</localRepository>

配置mirrors远程镜像

<mirror>  
      <id>alimaven</id>  
      <name>aliyun maven</name>  
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
      <mirrorOf>central</mirrorOf>          
</mirror>

配置profiles构建

<profile>
    <id>jdk-1.8</id>
    <activation>
        <jdk>1.8</jdk>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    </properties>
</profile>

如果你熟悉Maven的相关知识,那么你就应该知道,这几个配置应该放在什么地方,这里给出我的配置,你只是需要将jar地址改为你自己电脑上的地址就OK了

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
    <!-- 本地jar包地址,这里修改为你自己机器保存jar包的地址 -->
    <localRepository>/Users/yingside/work/m2_jar</localRepository>
  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
     <!-- 阿里镜像 -->
     <mirror>  
      <id>alimaven</id>  
      <name>aliyun maven</name>  
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
      <mirrorOf>central</mirrorOf>          
    </mirror> 
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->
    <profile>
          <id>jdk-1.8</id>
          <activation>
              <jdk>1.8</jdk>
              <activeByDefault>true</activeByDefault>
          </activation>
          <properties>
              <maven.compiler.source>1.8</maven.compiler.source>
              <maven.compiler.target>1.8</maven.compiler.target>
              <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
          </properties>
    </profile>
    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

做好上面的配置之后,在Eclipse里面的Maven配置中修改为我们自定义的Maven配置

修改Eclipse的Maven配置

-w628 将这个地方改为我们自定义的Maven的setttings.xml文件就可以了

安装Eclipse的Spring插件

从上面的快速开始我们可以看到,还需要在网上去下载一个Spring Boot的jar下载解压缩,再导入到我们自己的Eclipse中,那能不能直接创建一个Spring Boot工程呢?原生的Eclipse肯定是不行的,其实最方便的做法就是使用更加专业的IDE工具

  1. IntelliJ IDEA
  2. Spring Tool Suite

IntelliJ IDEA是现在最流行,最强大的java集成开发工具,可以很方便的开发代码,建议大家可以下载使用,当然这个软件最大的问题是收费的.这里就不再过多介绍

Spring Tool Suite其实就是把Spring工具集成好了的Eclipse,直接下载之后就能使用,和Eclipse一模一样,所以,我们也可以直接在已经存在的Eclipse工具上安装Spring工具

在已经存在的Eclipse上安装Spring工具

首先,你需要确定自己的Eclipse版本 -w751

然后在Spring网站,找到相对应的Eclipse Spring工具包 -w1059 在Eclipse中,安装Spring工具包 -w350 -w907 -w909 选中勾选的这几项 -w909 这些完成之后就可以开始升级了,可能需要一些时间,完成之后重新启动Eclipse -w1280

五.通过STS工具直接创建Spring Boot工程

安装好STS工具之后,New -> Other... 中就能看到Spring的相关选项 -w525

在接下来的页面中,其实就相当于会自动的到https://start.spring.io页面中创建Spring Boot项目 -w549 选择依赖包 -w549 -w264

本文链接:http://www.yanhongzhi.com/post/springboot-quick.html

-- EOF --