Thursday 1 August 2019

Spring Boot: Setting up the project for Web Application Development


Prerequisite
Install eclipse IDE
Install maven plugin to eclipse.

Step 1: Create new maven project.

Open Eclipse.

File -> New -> Other



Search for Maven.

Select ‘Maven Project’ and click on Next button.

Click on Next button.


Select ‘maven-archetype-quickstart’ artifact and click on Next button.


Give Group Id and Artifact Id as 'springbootApp', version as 1 and package name as 'com.sample.app' and click on Finish button.

Project structure created like below.

As you see my 'JRE System Library' is pointing to J2SE-1.5, I changed it to java 1.8 by following below steps.


Right click on ‘springbootApp’ project -> Properties.


Select ‘Java Build Path’ in left side of window, select ‘JRE System Library [J2SE-1.5] and click on Remove button.


Now click on ‘Add Library’ button, Select ‘JRE System Library’ and click on Next button.

Select ‘Java SE 8 [1.8.0_191] and click on Finish button.


Click on ‘Apply and Close’ button.

Now the project structure changed like below.


Step 2: Update pom.xml with spring boot dependencies.

My final pom.xml looks like below.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>springbootApp</groupId>
 <artifactId>springbootApp</artifactId>
 <version>1</version>
 <packaging>jar</packaging>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <name>springbootApp</name>
 <url>http://maven.apache.org</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>

 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
 </dependencies>
</project>

As you see pom.xml, I added ‘spring-boot-starter-parent’ as parent pom.
<parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>2.1.6.RELEASE</version>
</parent>

The spring-boot-starter-parent is a special starter that provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for “blessed” dependencies.

Since we are developing a web application, I added a spring-boot-starter-web dependency

<dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 3: Create a package ‘com.sample.app.controller’ and define HomeController.java like below.

HomeController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

 @RequestMapping("/")
 public String homePage() {
  return "Welcome to Spring boot Application Development";
 }

}


@RestController
The @RestController annotation is used to simplify the creation of RESTful web services.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

}

When you see the definition of RestController annotation, it combines both Controller and ResponseBody annotations.

@RequestMapping("/")
RequestMapping annotation is used to map web requests to java methods.

Step 4: Update App.java file (it is in com.sample.app package) like below.

App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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


SpringBootApplication is used to enable features like auto configuration, component scanning etc.,

Run App.java, you can see below messages in console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-07-05 09:23:42.080  INFO 94534 --- [           main] com.sample.app.App                       : Starting App on C02X902SJGH5 with PID 94534 (/Users/krishna/Documents/EclipseWorkSpaces/Learnings/springbootApp/target/classes started by krishna in /Users/krishna/Documents/EclipseWorkSpaces/Learnings/springbootApp)
2019-07-05 09:23:42.083  INFO 94534 --- [           main] com.sample.app.App                       : No active profile set, falling back to default profiles: default
2019-07-05 09:23:42.892  INFO 94534 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-05 09:23:42.919  INFO 94534 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-05 09:23:42.919  INFO 94534 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-05 09:23:43.000  INFO 94534 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-05 09:23:43.000  INFO 94534 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 873 ms
2019-07-05 09:23:43.208  INFO 94534 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-05 09:23:43.396  INFO 94534 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-05 09:23:43.399  INFO 94534 --- [           main] com.sample.app.App                       : Started App in 1.579 seconds (JVM running for 1.857)
2019-07-05 09:23:55.780  INFO 94534 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-07-05 09:23:55.780  INFO 94534 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-07-05 09:23:55.787  INFO 94534 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 7 ms


Open the url ‘http://localhost:8080/’ in browser, you can see below screen.


How come a spring boot web application starts from a main method?
Spring boot has embedded server (Default is tomcat).

Why should we move to container less (For Ex: tomcat container) deployments?
If you want to deploy a web application to a container like tomcat, jetty or jboss, you should perform below steps.
a.   Create a war file
b.   Setup the container. In real time, we may have three environments like development, testing and production. Containers should be setup for all these environments separately.

If you embed the container in your java application itself, you no need to setup any environment, you can run a web application, just like how you run hello world java application.

Note
Always put @SpringBootApplication class in root package and define all the components, services, controllers and daos in sub packages.

You can download complete working application from below link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment