Posted In: Spring, Spring Boot

Example – Create Eclipse + Spring Boot Application Step by Step

Technologies

Spring Boot
Eclipse Neon
MockMVC
Maven

Steps

1. Install Spring Tool Suite (STS) from Eclipse market place

2. Create New Project and Select ‘Spring Starter Project’

3. Choose packaging as War for web application

Steps 4,5 and 6 are only required for DB access.

4. Choose these options for web and db support. Select Web, MySQl, JDBC check boxes. In case you are not using any DB you don’t need below steps

5. Configure Spring Boot for MySQL

add following to application properties for your DB
spring.datasource.url=jdbc:mysql://localhost:3306/javausecase_db
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=true

6. Create JDBC class and assign JdbcTemplate. Now we can use JdbcTemplate to access DB

7. Create Services using Rest Controller

8. Run as Spring boot application

9. Test will rest client or with Spring Boot and Mock MVC test class

 1. Install Spring Tool Suite (STS) from Eclipse market place

2. Create New Project and Select ‘Spring Starter Project’

3. Choose packaging as War for web application

4. Choose these options for web and db support.

5. Change application properties

spring.datasource.url=jdbc:mysql://localhost:3306/javausecase_db
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=true

6. JDBC Access

package com.example.springapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class JdbcAccess {

	private final JdbcTemplate jdbcTemplate;

	@Autowired
	public JdbcAccess(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
		System.out.println("jdbcTemplate=" + jdbcTemplate);
		System.out.println(
		        "datasource=" + jdbcTemplate.getDataSource());
	}
}

7. REST services

package com.example.springapp;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExampleService {
	@RequestMapping(value = "/employee/list",
	        consumes = "application/json",
	        method = { RequestMethod.POST })
	public @ResponseBody Object getEmployeeList(
	        ServletRequest req, ServletResponse res,
	        @RequestBody String requestJson) throws Exception {
		System.out.println("getEmployeeList() called");
		return "{'response' : 'success'}";
	}

	@RequestMapping(value = "/employee/{employeeId}",
	        consumes = "application/json",
	        method = { RequestMethod.GET })
	public @ResponseBody Object getEmployee(ServletRequest req,
	        ServletResponse res,
	        @PathVariable("employeeId") int employeeId)
	        throws Exception {
		System.out.println("getEmployee() called");
		return "{'response' : 'success'}";
	}

	@RequestMapping(value = "/employee",
	        consumes = "application/json",
	        method = { RequestMethod.POST })
	public @ResponseBody Object insertEmployee(
	        ServletRequest req, ServletResponse res,
	        @RequestBody String requestJson) throws Exception {
		System.out.println("insertEmployee() called");
		return "{'response' : 'success'}";
	}

	@RequestMapping(value = "/employee",
	        consumes = "application/json",
	        method = { RequestMethod.PUT })
	public @ResponseBody Object updateEmployee(
	        ServletRequest req, ServletResponse res,
	        @RequestBody String requestJson) throws Exception {
		System.out.println("updateEmployee() called");
		return "{'response' : 'success'}";
	}

	@RequestMapping(value = "/employee",
	        consumes = "application/json",
	        method = { RequestMethod.DELETE })
	public @ResponseBody Object deleteEmployee(
	        ServletRequest req, ServletResponse res,
	        @RequestBody String requestJson) throws Exception {
		System.out.println("deleteEmployee() called");
		return "{'response' : 'success'}";
	}
}

8. Run as Spring boot application

TEST

9. Test using REST client

10. We can also test it with Spring Boot Test and Mock MVC. Run it as JUNIT test. No need to start server. Spring Boot will take care of it.

package com.example.springapp;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class Example201715ApplicationTests {

	@Autowired
	private MockMvc mvc;

	@Test
	public void contextLoads() {
	}

	@Test
	public void testGetEmployee() throws Exception {

		mvc.perform(MockMvcRequestBuilders.get("/employee/1")
		        .accept(MediaType.TEXT_HTML)
		        .contentType(MediaType.APPLICATION_JSON))
		        .andExpect(status().isOk())
		        .andExpect(content().string(
		                equalTo("{'response' : 'success'}")));
	}

	@Test
	public void testGetEmployeeList() throws Exception {

		mvc.perform(MockMvcRequestBuilders.post("/employee/list")
		        .accept(MediaType.TEXT_HTML)
		        .contentType(MediaType.APPLICATION_JSON)
		        .content("{}")).andExpect(status().isOk())
		        .andExpect(content().string(
		                equalTo("{'response' : 'success'}")));
	}

}

Tags: , ,

by , on February 7th, 2017

  • Categories