[Java] Try Spring Boot 1 (Environment construction ~ Tomcat startup)

6 minute read

Introduction

I would like to write a sample program in Spring Boot. Please refer to Spring thorough introduction. We will make the conference room reservation system introduced here.

Install Java

Let’s install Java. There are various versions, but this time we will use OpenJDK 8. If you are using WSL2, you can download it with the following command.

WSL2


$ sudo apt install openjdk-8-jdk

Next, set the environment variables. First, let’s check where Java is installed.

WSL2


$ dpkg -L openjdk-8-jdk

*** abbreviation
/usr/lib/jvm/java-8-openjdk-amd64
*** abbreviation

There are a lot of them, but it is OK to specify JAVA_HOME with /usr/lib/jvm/java-8-openjdk-amd64. Now that you know the path, set the environment variables.

WSL2


$ sudo vi /etc/profile

Add the following to /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

Use the following command to reflect the bash settings and confirm that the installation is complete.

WSL2


$ 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)

Now you can use Java.

Install Maven

Next, install Maven. It seems that Gradle is becoming more popular as a build tool, but I use good old Maven because of my adult circumstances. This is the only command.

WSL2


$ sudo apt install maven

Let’s confirm the installation.

WSL2


$ 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"

Start Spring-Boot sample

Let’s create a Spring Boot sample project. First, create an appropriate directory. In my case, I did the following.

WSL2


$ cd ~
$ mkdir web-app
$ cd web-app

Create a sample project with the following command.

WSL2


$ mvn archetype:generate

*** Omitted ***

Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1672:

How about. A lot of English comes out and I’m scared, but you can ignore it. mvn archetype:generate is a command to create a project interactively. Let’s select the sample to be used this time. Try typing spring-boot.

WSL2


Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): :spring-boot

There are fewer choices than before. (78 in my environment) This time, let’s use org.springframework.boot:spring-boot-sample-tomcat-archetype (Spring Boot Tomcat Sample). This sample has Tomcat built in, so you can run Jar as is. In my environment, it was displayed as 68:, so enter 68. (It should be possible to specify the name)

WSL2


*** abbreviation
68: remote -> org.springframework.boot:spring-boot-sample-tomcat-archetype (Spring Boot Tomcat Sample)
*** abbreviation
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): :68

I’m going to speak a lot of English again You can ignore it. Next you will be asked:

WSL2


*** abbreviation
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 requires specification of groupId, artifactId, version, and package. It is used as a package name. I think that essentially anything is OK. If you just press Enter for version and package, they will be reflected automatically. This time, I will not explain the setting items of Maven, but I recommend this book for those who want to know Maven. [Introduction to Java Build Tool](https://www.amazon.co.jp/Java%E3%83%93%E3%83%AB%E3%83%89%E3%83%84%E3%83%BC(%E3%83%AB%E5%85%A5%E9%96%80-Maven-Gradle-SBT-Bazel%E5%AF%BE%E5%BF%9C/dp/4798049387) If the following message is displayed on the console, it is successful.

WSL2


[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] ----------------------------------------------- -------------------------

Let’s package the resulting file.

WSL2


$ cd mvn-spring
$ mvn package

*** abbreviation

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

BUILD FAILUREと出ました。コンソールを確認してみましょう。

Failed tests:
  SampleTomcatApplicationTests.testHome:53 expected:<Hello [World]> but was:<Hello [DESKTOP-F147IF8]>
  NonAutoConfigurationSampleTomcatApplicationTests.testHome:82 expected:<Hello [World]> but was:<Hello [DESKTOP-F147IF8]>

どうやらテストに失敗しているようです。expected:<Hello [World]> but was:<Hello [DESKTOP-F147IF8]>となっているので、’Hello World’と返すようにコードを直してあげましょう。(なぜサンプルなのにエラーを吐く…) まずはテストコードを確認します。

SampleTomcatApplicationTests.java


/*
 * 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())がエラーとなっているテストなので、ここのテストが通るように修正します。

HelloWorldService.java


/*
 * 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”とベタ打ちしました。 本質的には解決していませんが、とりあえず動くようにならないと始まらないのでこのまま進めます。 もう一度パッケージ化してみましょう。

WSL2


$ 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] ----------------------------------------------- -------------------------

This time it was successful. If successful, a new target folder will be created. The executable jar is stored here. Let’s move it immediately.

WSL2


$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] crtomcat.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[email protected]414be896: startup date [Sun Sep 06 17:01:19 JST 2020]; root of context hierarchy

A fun startup script is displayed. By default, Tomcat starts on port 8080, so let’s access it. Enter http://localhost:8080 in your browser. If you see Hello World, you are successful. Stop the Tomcat by pressing Ctrl + C on the console and you’re done.

At the end

I finished creating a conference room booking app, running the Tomcat sample… Next time, I would like to extend and develop this sample! (If it frustrates, it may not be an article)