Technology

Java Spring Boot – Quick look

Spring Boot aims to simplify Spring development and it is for all Java developers. Spring Boot has a way of making Spring more approachable even to those new to Spring

Spring Boot makes it easy to create Spring-powered, production-grade applications and services with the absolute minimum fuss. It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need.

Prerequisites :

  • If you have Eclipse, download the Spring boot plug-in From Eclipse
  • Help -> Eclipse Marketplace -> Spring Boot -> Spring Tools 4
  • If you don’t have Eclipse, download Spring Tool Suite [STS] from here
  • Download the latest JDK from here.

Create a Spring Boot Project :

Online References: Tutorial / Youtube

Using Eclipse

  1. Click (File->New->other->wizard->Spring Starter Project).
  2. Select Type as Maven [ You can use Maven or Gradle ]
  3. Enter Name, Group, and Artifact & click Next
  4. Select Maven Dependencies {Most widely used are Web, JPA, SQL}
  5. Click Finish.

Using Spring Initializer

  1. Open Spring Initializer click
  2. Enter Group Id, Artifact Id , Name and Other Details are Automatically Updated
  3. Select the Required Dependencies
  4. Click Generate Project
  5. In Eclipse Click File -> Import ->Exixting Maven Projects -> Choose the Root Directory -> Finish

NOTE : First Thing is to see POM.XML page and checks whether all the MAVEN dependencies are added correctly.

If you need more dependencies Go to MAVEN Repository in Chrome and Copy the required dependency and paste into POM.XML page

Right click -> Maven -> Update Project

Creating Classes for Application

  1. Create a new Class [Model Class] which includes Variables , Getters and Setters, Constructors
  2. Create a new Controller class in src/main/java package (or) create a new package/Class in src/main package
  3. Create a new Service Class if required
  4. Create a Repository class if required

SPRING BOOT STRUCTURE 

 

HTTP GET request :

 

 

Sample Code For GET API :
@RestController
public class TopicController {
@Autowired
private TopicService topicService;
@RequestMapping(“/topics/{id}”) // Default Request is GET
public Topic getTopic(@PathVariable String id)
{
    return topicService.getTopic(id);
}
}

 

HTTP POST request :

Now Create a POST API in Controller Class

 

Sample Code For POST API :
@RequestMapping(method = RequestMethod.POST, value = “/topics”)
public Topic addTopic(@RequestBody Topic topic) {
     topicService.addTopic(topic);
     return topic; //Testing
}

 

NOTE : You can use Postman for API requests.

How to Run the Spring Boot Application

Right Click the Application → Run as -> Java Application

APPLICATION PROPERTIES :

Note: If you are Using External Database like SQL
Include SQL dependency
Write the following Code in Application Properties which is in

Src / main / resources :

spring.datasource.url=jdbc:mysql://localhost:3306/emp?useSSL=false
##emp — database name
spring.datasource.username=root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Inno DBDialect
logging.level.org.hibernate.SQL=debug

Spring Boot Testing :

  • Basic Test Framework — JUnit
  • Mocking — Mockito
  • Assertion — AssertJ, Hamcrest
  • Spring Unit Test Framework — Spring Test

JUnit Testing

Create a new class in Src/test/java for Testing

GET API Testing :

Sample Code for GET API Testing
@RunWith(SpringRunner.class)
@WebMvcTest(value = TopicController.class, secure = false)
public class TopicControllertest {
@Autowired
private MockMvc mockMvc;
@MockBean
private TopicService topicService;
@Test
public void GETbyId() throws Exception {
mockMvc.perform(get("/topics/id").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", Matchers.is("js")))
.andExpect(jsonPath("$.name",Matchers.is("js framework")))
.andExpect(jsonPath("$.description",Matchers.is("describe js")));
}

POST API TESTING:

Sample Code for POST API Testing
@Test
public void addTopictest() throws Exception {
String json= "{"\"id\":\"js\"," \"name\":\"js framework\",
"\"description\":\"describe js\"}";
mockMvc.perform(post("/topics/")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id",Matchers.is("js")))
.andExpect(jsonPath("$.name",Matchers.is("js framework")))
.andExpect(jsonPath("$.description",Matchers.is("describe js")));
}

Note: To Run the Test: Save & Right click newly created Test Class and Click Run as -> Junit Testing

HTTP STATUS

200 — Success — The request has succeeded

201 — Created — The request has been fulfilled and resulted in a new resource being created

204 — No Content — The request has fulfilled the request but does not need to return an entity body

400 — Bad request — The request could not be understood by the server due to malformed syntax

404 — Not Found — The server has not found anything matching the request URI

405 — Method Not allowed — The method specified in the request is not allowed for the resource identified by the request URI

Mostly Occuring Errors :

Problem : Communication link Failure && Connection refused: connect
Reason: Database & Server is not Connected to Application
Solution: Connect the application with database

Problem : Application failed to start
Reason: Started running the Application without stopping the previously    running application because Tomcat server post is already running.
Solution: Stop the Previously running Application and Run the Application.

Problem: Dependency Injection
Reason : Driver gets Deprecated
Solution: Update the Project…Right Click ->Maven -> Update Project

Testing Problem :java.lang.AssertionError: No value at JSON path “$.id”
Solution : Return data in Post Method

OTHER REFERENCES :

  1. Tutorial : Learn Spring Boot
  2. Youtube : Learn Spring Boot
  3. Testing : JUnit Testing
  4. Testing : Junit Testing

MY PROJECTS :

  1. Course details — GIT HUB
  2. Employee with Database — GIT HUB
  3. Student Page — GIT HUB

 

2 thoughts on “Java Spring Boot – Quick look”

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × four =