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

Introduction

I would like to write a sample program in Spring Boot. For reference, [Introduction to Spring](https://www.amazon.co.jp/Spring%E5%BE%B9%E5%BA%95%E5%85%A5%E9%96%80- Spring-Framework% E3% 81% AB% E3% 82% 88% E3% 82% 8BJava% E3% 82% A2% E3% 83% 97% E3% 83% AA% E3% 82% B1% E3% 83% BC% E3% 82% B7% E3% 83% A7% E3% 83% B3% E9% 96% 8B% E7% 99% BA-% E6% A0% AA% E5% BC% 8F% E4% BC% 9A % E7% A4% BENTT% E3% 83% 87% E3% 83% BC% E3% 82% BF / dp / 4798142476). We will create the conference room reservation system introduced here.

Java installation

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

Then set the environment variables. First, let's check where Java was installed.

WSL2


$ dpkg -L openjdk-8-jdk

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

There are a lot of them, but you can specify JAVA_HOME in / usr / lib / jvm / java-8-openjdk-amd64. Now that we know the path, set the environment variables.

WSL2


$ sudo vi /etc/profile

/etc/Add the following to 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 check that the installation has been completed.

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.

Maven installation

Next, install Maven. Gradle seems to be more popular as a build tool, but due to adult circumstances, I use good old Maven. This is the only command.

WSL2


$ sudo apt install maven

Let's check 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

Now let's create a Spring Boot sample project. First, create a suitable 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

***Omission***

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

How about. A lot of English comes out and I'm afraid, 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 options than before. (78 in my environment) This time, let's use ʻorg.springframework.boot: spring-boot-sample-tomcat-archetype (Spring Boot Tomcat Sample) . In this sample, Tomcat is built in, so you can run Jar as it is. In my environment, it was displayed as 68:, so enter 68`. (You should be able 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 can speak a lot of English again, but please don't turn down. You can ignore it. Next you will be asked the following.

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 you to specify groupId, ʻartifactId, version, package. It is used in the package name. I think that essentially anything is OK. If you press Enter as it is, version and package` will be reflected without permission. I will not post an explanation of Maven setting items this time, but if you want to know about Maven, I recommend this book. [Introduction to Java Build Tools](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

I got BUILD FAILURE. Let's check the console.

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

Apparently the test is failing. ʻExpected: <Hello [World]> but was: <Hello [DESKTOP-F147IF8]>`, so let's fix the code so that it returns'Hello World'. (Why is it a sample but throws an error ...) First, check the test code.

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());
	}

}

Since assertEquals ("Hello World ", entity.getBody ()) is a test with an error, modify it so that this test passes.

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"; //Modification place
	}

}

This time, I solidified it as "Hello World" to avoid the test. In essence, it has not been solved, but it will not start unless it works for the time being, so I will proceed as it is. Let's package it again.

WSL2


$ mvn package

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

You'll see a fun startup script. Tomcat starts on port 8080 by default, so let's access it. Type http: // localhost: 8080 in your browser. If you see Hello World, you are successful. Press Ctrl + C on the console to stop Tomcat and you're done.

At the end

I said that I would create a conference room reservation app, but I finished running the Tomcat sample ... I would like to extend and develop this sample from the next time onwards! (If you get frustrated, it may not be an article)

Recommended Posts

Try Spring Boot 1 (Environment construction ~ Tomcat startup)
[Spring Boot] Environment construction (macOS)
Docker × Spring Boot environment construction
◆ Spring Boot + gradle environment construction memo
[Spring] Environment construction
Spring Boot environment construction memo on mac
Spring Boot + Docker Java development environment construction
Try Spring Boot from 0 to 100.
Try using Spring Boot Security
Try Spring Boot on Mac
Database environment construction with Docker in Spring boot (IntellJ)
Try running Spring Boot on Kubernetes
Processing at application startup with Spring Boot
Java runtime environment construction method (Tomcat @ Linux)
Create Spring Boot development environment on Vagrant
Spring Boot 2.0.0 does not start built-in tomcat
[Environment construction] Spring Tool Suite4 installation (Mac)
Try running ScalarDB on WSL Ubuntu (Environment Construction)
SameSite cookie in Spring Boot (Spring Web MVC + Tomcat)
About designing Spring Boot and unit test environment
[Java] Environment construction
JAVA + STS (Spring Tool Suite) environment construction procedure
Try LDAP authentication with Spring Security (Spring Boot) + OpenLDAP
Java environment construction
Challenge Spring Boot
Build Spring Boot project by environment with Gradle
Spring Boot Form
Try to automate migration with Spring Boot Flyway
Spring Boot Memorandum
Create Spring Boot environment with Windows + VS Code
gae + spring boot
Docker environment construction
LINE Bot x Java (Spring Boot) construction procedure
Create a Spring Boot development environment with docker
Java development environment construction (Mac + Pleiades All in One Eclipse 4.7 + Spring Boot + Gradle (Buildship))
Spring Boot application built-in Tomcat, Apache and WebSocket integration
Please note that Spring Boot + Tomcat 8.5.8 cannot be used!
Switch environment with Spring Boot application.properties and @Profile annotation
Try using OpenID Connect with Keycloak (Spring Boot application)
SSO with GitHub OAuth in Spring Boot 1.5.x environment
Try Dependency Inversion Principle with Multiple Spring Boot Projects
Try gRPC in Spring Boot & Spring Cloud project (Mac OS)
Deploy the Spring Boot project to Tomcat on XAMPP
How to boot by environment with Spring Boot of Maven
Java + Spring development environment construction with VirtualBox + Ubuntu (Xfce4)
Penronse environment construction [Windows]
[Environment construction] Eclipse installation
SPRING BOOT learning record 01
Spring Boot + Heroku Postgres
[Flutter] Ubuntu 20.04 environment construction
Rails Docker environment construction
Spring boot memo writing (1)
First Spring Boot (DI)
Spring Boot2 cheat sheet
Spring Boot Servlet mapping
Spring Boot learning procedure
Circle CI environment construction
Spring boot memo writing (2)
java development environment construction
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability