Dev-Mind

Spring in practice : introduction (EN)

04/10/2018
Java  Spring 

Since the beginning, Spring has been a set of tools designed to simplify the development of Java applications in companies or not. The last versions of Spring supports other languages on the JVM like Groovy or Kotlin.

Online training

dev-mind.fr tab student (étudiant)
> https://dev-mind.fr/help.pdf

spring intro

Introduction

Requirements

To be able to learn Spring you must have

  • some basics in Java and JEE

  • know unit testing in Java

  • have knowledge of the Web

  • know about JDBC and Hibernate

  • a PC with a good IDE (IntelliJ, Netbeans …​)

What’s Spring ?

Spring is the most used Java framework

canvas

A framework comes with rules to organize developments

  • Good practices

  • Abstraction of the complexity

  • Provides utility classes

  • Helps to focus on the business code and not on the technical plumbing

Spring is

  • a Java framework

  • an entire ecosystem

  • a community

  • a company

Spring framework

Make Java development easier

icon spring framework
  • Spring Core provides a framework to simplify project technical aspects

  • Sub-projects deal with more specific technical issues

  • Nothing is mandatory, everything is configurable

  • Big effort on backward compatibility

  • Spring Frmaework 5.0 and JDK> 1.8

An entire ecosystem

canvas
  • Spring Batch

  • Spring Mobile

  • Spring LDAP

  • Spring Social

  • Spring web services

  • …​

Open source project

Start a project

Generate

To start a new project, you can (you should) use the official generator https://start.spring.io/

springboot init19

Use these settings

  • Project : Gradle project

  • Language : Java

  • Spring Boot : the highest (not suffixed snapshot)

  • Project metadata: you have to define a group com.emse.spring, an artifact name faircorp. If you click on the options you can select the targetted Java version (use 1.8 or 1.11)

  • dependencies: Spring Web, Spring Boot DevTools

Click on the Generate button

springboot init191

Import in your IDE

  1. Unzip the project into a directory (you can put it next to the first project we did in the TPs)

  2. Open the project in an IDE

springboot ide

springboot tree

  • Follow the maven convention for source directories

  • Configure Gradle

    • Gradle Wrapper (gradle directory, gradlew, gradlew.bat)

    • build.gradle, settings.gradle

  • Application is generated with tests
     

Gradle configuration

settings.gradle

rootProject.name = 'faircorp'
  • contains the project name

  • can also contain the sub modules definition
    avec include 'backend', 'frontend'

build.gradle (1/3)

plugins {
	id 'org.springframework.boot' version '2.2.1.RELEASE' // 1
	id 'io.spring.dependency-management' version '1.0.8.RELEASE' // 2
	id 'java' // 3
}

<1> Adds the Spring Boot plugin to be able to manage your app with Gradle
<2> Adds Spring dependency management plugin to use the compatible dependencies
<3> Adds the Java plugin to help Gradle to manage our app lifecyle

build.gradle (2/3)

group = &apos;com.emse.spring&apos; // 1
version = &apos;0.0.1-SNAPSHOT&apos;
sourceCompatibility = 1.8

configurations {  // 2
	developmentOnly
	runtimeClasspath {
		extendsFrom developmentOnly
	}
}

repositories { // <b class="conum">(3)</b>
 mavenCentral()
}

<1> Project id
<2> a new configuration to be able to define dependencies only uses in development mode
<3> Libraries repository which contain a lot of libraries

build.gradle (3/3)

dependencies { // 1
 implementation &apos;org.springframework.boot:spring-boot-starter-web&apos; // 2
 developmentOnly &apos;org.springframework.boot:spring-boot-devtools&apos; // 3
 testImplementation(&apos;org.springframework.boot:spring-boot-starter-test&apos;) { //4
    exclude group: &apos;org.junit.vintage&apos;, module: &apos;junit-vintage-engine&apos;
 }
}

test {
	useJUnitPlatform()
}

1.  spring-boot-starter-web is a starter used to create WebApp
 
2. spring-boot-devtools is a tool set which help when you develop (live reload or automatic restart)
 
3. spring-boot-starter-test is the starter that imports dependencies used in the tests (SpringTest, Junit, Mockito …​). This configuration exclude all Junit versions and activate the last one

FaircorpApplication

@SpringBootApplication
public class FaircorpApplication {

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

}
  • @SpringBootApplication initialize a Spring Boot application. This is the main class

FaircorpApplicationTests

@RunWith(SpringRunner.class) // <1>
@SpringBootTest // <2>
public class FaircorpApplicationTests {

	@Test
	public void contextLoads() {
	}

}
  1. Runner to use when we want to test a Spring class

  2. Annotation which creates an application context dedicated for tests

application.properties

  • This file is in src/main/resources, it contains all the application properties
    > A property has a key and a value. In your code you read a property by its key. At runtime you have the value
    > Properties help to customize app on a particular environment+  

  • If you have an application-prod.properties file, it will be into account only when the prod profile will be activated

Launch application

./gradlew --continuous bootRun // <1>

[...]
INFO 9740 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
INFO 9740 --- [  restartedMain] f.i.tc.s.SpringBootIntroApplication : Started SpringBootIntroApplication in 2.971 seconds
<==========---> 80% EXECUTING
&gt; :bootRun  // <2></2></==========---></1>
  • the --continuous gradle option will restart the server when we recompile the project

  • the build gets "stuck" at 80%, but the server is actually started and ready to accept connections

  • To stop the application use kbd: [Ctrl + c]

Application packaging

Gradle helps to generate a web archive and it can deploy this archive on an application server

mvc deploy

This is the past…​ now

With Spring Boot, an app should be autonomous, this is the convention.

mvc run
./gradlew assemble
  • This task generate a jar (Java archive) in build/libs.

  • jar name is faircorp-0.0.1-SNAPSHOT.jar. It contains everything you need to launch the application (conf + libs)

  • To launch your Spring Boot App you can execute

java -jar build/libs/faircorp-0.0.1-SNAPSHOT.jar

Lab 1 : generate a new app

The aim is to build a Spring Boot application called FairCorp

faircorp
  • Use the Spring generator

  • Import the app in IntelliJ

  • Use the different ways to launch app (gradlew, java -jar, IDE)

  • Open URL localhost:8080 in your browser
    You should see a message "Whitelabel Error Page", Don’t panic : since we’ve defined no web endpoint, Spring answers with a custom HTTP 404 error message…​ We’re going to understand what happened

  • Launch tests in your IDE

  • Create a new file in src/main/resources/static. The name will be index.html

  • In this file copy the following code

<html>
    <head>
        <title> Spring in practice</title>
    </head>
    <body>
        Hello world
    </body>
</html>
  • Recompile your code or restart your app

  • Reopen localhost:8080 in your browser

Next labs

During all your courses (Java, Spring, Web, IOT, Security…​) you will develop a real app on a concrete case

tp

In this app, you will manage ligths of a building. You have several rooms by floor and each room can have one or several lights.

For each room we want to know the lights and their steps (off or on). If a lamp is on, we want to have the brightness. We want to pilot each lights from this app.

In the next chapters we will do that

Understand what’s happened

In few lines you have started your first Spring project. I spoke about Spring, Spring Framework, Spring Boot…​ But what’s the difference ?

Spring Framework

is a popular, open-source, Java-based application framework - we saw before that we have many other projects for big data, storing data, securing applications, and more!

Spring based applications have a lot of configuration.

Spring Boot

takes an opinionated view of the Spring platform and third-party libraries.

With Spring Boot, it’s easy to create applications for all types of workloads. Most Spring Boot applications need very little Spring configuration.

Spring Boot is a "convention over configuration" type of framework, with no code generation.

When we use Spring MVC (the original web framework built on the Servlet API) for example, we need to configure for example the dispatcher servlet among other things.
When we use the Spring support of Hibernate/JPA, we would need to configure a datasource, an entity manager factory, a transaction manager…​

Spring Boot simplifies all of these configuration elements, by auto-configuration. For example, when it sees spring-webmvc on the classpath, Spring Boot adds automatically @EnableWebMvc on your context.

With Spring boot we will use starters

dependencies {
 compile(&apos;org.springframework.boot:spring-boot-starter-web&apos;)
 testCompile(&apos;org.springframework.boot:spring-boot-starter-test&apos;)
}

The starter name starts by spring-boot-starter-XXXX and use a suffix XXXX (web, cache, data-jpa, mustache, web…​)

In the next course we will see how to add objects to our app and how we can linked them each other…​