在本章中,我们将介绍如何搭建 Spring Boot 环境并启动 Tomcat 服务器来进行第一次尝试
首先
我想用Spring Boot编写示例程序。
参考资源是《Spring徹底入門》。
我们将要制作这里介绍的会议室预订系统。
安装Java
让我们安装Java,有很多版本可以选择,但这次我们选择OpenJDK 8。如果你正在使用WSL2,可以使用以下命令进行下载。
$ sudo apt install openjdk-8-jdk
我们接下来要设置环境变量。
首先,我们先确认一下Java是否已经安装在哪个位置。
$ dpkg -L openjdk-8-jdk
*** 略
/usr/lib/jvm/java-8-openjdk-amd64
*** 略
尽管会出现很多结果,但在JAVA_HOME中指定/usr/lib/jvm/java-8-openjdk-amd64就可以了。既然路径已经找到了,我们可以设置环境变量。
$ sudo vi /etc/profile
/etc/profileに以下を追記。
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=.:$JAVA_HOME/jre/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar
让我们使用以下命令来应用bash的设置并确认它已成功安装。
$ source /etc/profile
$ java -version
openjdk version "1.8.0_265"
OpenJDK Runtime Environment (build 1.8.0_265-8u265-b01-0ubuntu2~20.04-b01)
OpenJDK 64-Bit Server VM (build 25.265-b01, mixed mode)
我现在可以使用Java了。
安装Maven
接下来,我们将安装Maven。
虽然作为构建工具,Gradle更受欢迎,但基于某些成年人的情况,我们将使用经典而可靠的Maven。
仅需运行如下命令。
$ sudo apt install maven
我们来确认一下是否已经安装。
$ mvn -v
Apache Maven 3.6.3
Maven home: /usr/share/maven
Java version: 1.8.0_265, vendor: Private Build, runtime: /usr/lib/jvm/java-8-openjdk-amd64
Default locale: en, platform encoding: UTF-8
OS name: "linux", version: "4.19.104-microsoft-standard", arch: "amd64", family: "unix"
启动Spring Boot示例程序。
那么,让我们创建一个SpringBoot示例项目。
首先,创建一个适当的目录。根据我个人的情况,我会这样做。
$ cd ~
$ mkdir web-app
$ cd web-app
用以下的指令创建一个示例项目。
$ mvn archetype:generate
*** 中略 ***
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1672:
你觉得如何?虽然有很多英文出现可能会有点吓到,但可以忽略不计,没关系。
mvn archetype:generate是用来交互式创建项目的命令。
这次我们选择要使用的示例吧。试试输入spring-boot。
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : spring-boot
刚才的选择变少了。(在我的环境中,只剩下78个选项)
这次我们来试试 org.springframework.boot:spring-boot-sample-tomcat-archetype (Spring Boot Tomcat Sample)。
这个示例中已经集成了Tomcat,所以可以直接运行Jar文件。
在我的环境中显示为68:,所以输入68。(应该也可以通过指定名称来实现)
*** 略
68: remote -> org.springframework.boot:spring-boot-sample-tomcat-archetype (Spring Boot Tomcat Sample)
*** 略
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 68
虽然会有很多英文出现,但请不要灰心。可以不理会它们,没关系。
接下来会被问到以下问题。
*** 略
Define value for property 'groupId': com.rocorock
Define value for property 'artifactId': mvn-spring
Define value for property 'version' 1.0-SNAPSHOT: :
Define value for property 'package' com.rocorock: :
Confirm properties configuration:
groupId: com.rocorock
artifactId: mvn-spring
version: 1.0-SNAPSHOT
package: com.rocorock
Y: : y
在Maven中,需要指定groupId、artifactId、version和package。这些会在包名等地方被使用。本质上,任何设定都可以。version和package只要按下Enter键,就会自动应用。本次不会介绍Maven的设置项说明,但如果想了解Maven的相关知识,我推荐这本书《Java构建工具入门》。如果控制台打印出以下内容,那么表示成功。
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: spring-boot-sample-tomcat-archetype:1.0.2.RELEASE
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.rocorock
[INFO] Parameter: artifactId, Value: mvn-spring
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: com.rocorock
[INFO] Parameter: packageInPathFormat, Value: com/rocorock
[INFO] Parameter: package, Value: com.rocorock
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: groupId, Value: com.rocorock
[INFO] Parameter: artifactId, Value: mvn-spring
[INFO] Project created from Archetype in dir: /home/tomoya/web-app/mvn-spring
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:26 min
[INFO] Finished at: 2020-09-06T16:51:46+09:00
[INFO] ------------------------------------------------------------------------
我们来把已完成的文件打包成一个包。
$ cd mvn-spring
$ mvn package
*** 略
Results :
Failed tests:
SampleTomcatApplicationTests.testHome:53 expected:<Hello [World]> but was:<Hello [DESKTOP-F147IF8]>
NonAutoConfigurationSampleTomcatApplicationTests.testHome:82 expected:<Hello [World]> but was:<Hello [DESKTOP-F147IF8]>
Tests run: 2, Failures: 2, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.461 s
[INFO] Finished at: 2020-09-06T16:52:06+09:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.15:test (default-test) on project mvn-spring: There are test failures.
[ERROR]
[ERROR] Please refer to /home/tomoya/web-app/mvn-spring/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
构建失败。让我们检查控制台。
Failed tests:
SampleTomcatApplicationTests.testHome:53 expected:<Hello [World]> but was:<Hello [DESKTOP-F147IF8]>
NonAutoConfigurationSampleTomcatApplicationTests.testHome:82 expected:<Hello [World]> but was:<Hello [DESKTOP-F147IF8]>
看起来你的测试失败了。期望是: 但实际是:,所以我们要修复代码,使其返回 ‘Hello World’。(为什么示例会有错误呢…)
首先我们来检查测试代码。
/*
* Copyright 2012-2014 the original author or authors.
*
* Licensed 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.
*/
package com.rocorock.tomcat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
/**
* Basic integration tests for demo application.
*
* @author Dave Syer
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleTomcatApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
@DirtiesContext
public class SampleTomcatApplicationTests {
@Value("${local.server.port}")
private int port;
@Test
public void testHome() throws Exception {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity(
"http://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("Hello World", entity.getBody());
}
}
由于assertEquals(“Hello World”, entity.getBody())出现错误,所以需要修正这个测试,使得该测试通过。
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed 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.
*/
package com.rocorock.tomcat.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class HelloWorldService {
@Value("${name:World}")
private String name;
public String getHelloMessage() {
return "Hello World"; //修正箇所
}
}
为了避免考试,这次我直接输入了“Hello World”。
虽然本质上问题没有解决,但是只有开始动起来才能继续下去,所以就这样进行吧。
让我们再次尝试进行打包。
$ mvn package
*** 略
[INFO] Building jar: /home/tomoya/web-app/mvn-spring/target/mvn-spring-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.0.2.RELEASE:repackage (default) @ mvn-spring ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.288 s
[INFO] Finished at: 2020-09-06T17:00:47+09:00
[INFO] ------------------------------------------------------------------------
这次成功了。成功后会创建一个新的target文件夹。可执行的jar文件保存在这里。现在就来试试吧。
$ ls
pom.xml src target
$ java -jar target/mvn-spring-1.0-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.0.2.RELEASE)
2020-09-06 17:01:19.928 INFO 5988 --- [ main] c.r.tomcat.SampleTomcatApplication : Starting SampleTomcatApplication on DESKTOP-F147IF8 with PID 5988 (/home/tomoya/web-app/mvn-spring/target/mvn-spring-1.0-SNAPSHOT.jar started by tomoya in /home/tomoya/web-app/mvn-spring)
2020-09-06 17:01:19.951 INFO 5988 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@414be896: startup date [Sun Sep 06 17:01:19 JST 2020]; root of context hierarchy
在系统上会显示一个有趣的启动脚本。由于Tomcat默认在端口8080上启动,因此让我们尝试访问它。
请在浏览器中输入http://localhost:8080。如果显示”Hello World”,则表示成功。
如果你在控制台上按下Ctrl + C停止Tomcat,那么演示结束了。
结束
虽然说要开发一个会议室预约应用程序,但是最后只是运行了Tomcat的示例就结束了…
下次我打算在这个示例的基础上进行扩展和开发!(如果遇到挫折的话可能不会成为一篇文章)