Advantages |
- Reduce Developement, Testing time and efforts.
- Avoid lots of maven imports and the various version conflicts.
- Quick start to development by providing defaults.
- No Separate Web Server Needed.Which means that you no longer
have to boot up Tomcat, Glassfish, or anything else.
- Requires less configuration-Since there is no web.xml file.
Simply add classes annotated with @Configuration and then you can add
methods annotated with- @Bean, and Spring will automagically load up the
object and manage it like it always has. You can even add @Autowired
to the bean method to have Spring autowire in dependencies needed for
the bean.
- Environment Based Configuration-Using these properties, you
can pass into the application which environment you are using
with:-Dspring.profiles.active={enviornment}. Spring will then load up
the subsequent application properties file at
(application-{environment}.properties) after loading up the main
application properties file.
- No need to make Dispatcher servlet, Easy mapping, Jackson
|
Main Modules |
- Initializr
- Web tools
- Dev tools
- Actuator
- HATEOAS
- JPA / JDBC
|
How to deploy Spring boot service |
- Compile and build with maven
- Containerize with docker command (optional. should have yaml file existing)
- Deploy with kubectl command or other cloud shell (should have yaml file existing)
|
How to run Spring boot application to custom port? |
server.port=8090
|
How to test Spring Boot service |
- Use spring-boot-starter-test dependency
- Use generated test for application and extend
- Rus as JUnit test case
Code
// Generated class
@SpringBootTest
public class SpringBootHelloWorldTests {
@Test
public void contextLoads() { }
}
// Extension class
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
public class TestWebApp extends SpringBootHelloWorldTests {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testEmployee() throws Exception {
mockMvc.perform(get("/employee")).andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("emp1")).andExpect(jsonPath("$.designation").value("manager"))
.andExpect(jsonPath("$.empId").value("1")).andExpect(jsonPath("$.salary").value(3000));
}
}
|
How to implement Pagination and Sorting with Spring Boot?
|
Using the Spring Data-JPA this is achieved passing pageable org.springframework.data.domain.Pageable to the repository methods.
Code
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.javainuse.data.EmployeeRepository; // REPOSITORY
import com.javainuse.model.Employee; // ENTITY
@RestController // Controller
public class EmployeeController {
@Autowired
private EmployeeRepository employeeData;
@RequestMapping(value = "/listPageable", method = RequestMethod.GET)
Page<Employee> employeesPageable(Pageable pageable) {
return employeeData.findAll(pageable);
}
}
|
What is Swagger? Have you implemented it using Spring Boot? |
Swagger is widely used for visualizing APIs, and with Swagger UI it provides online sandbox for frontend developers. Swagger is a tool, a specification and a complete framework implementation for producing the visual representation of RESTful Web Services. It enables documentation to be updated at the same pace as the server. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Thus Swagger removes the guesswork in calling the service.
Usually as simple as add a dependency
org.springdoc
springdoc-openapi-starter-webmvc-ui
|
What is Spring Profiles? How do you implement it using Spring Boot?
Different ways
|
Use spring.profiles.active=dev in application properties and annotation:
@Profile("dev") in JavaConfig classes for different profiles.
OR use Cloud Config server
spring.config.import=optional:configserver:http://localhost:8888
need spring-cloud-starter-config dependency
|
How to implement Exception Handling using Spring Boot?
|
Spring customize and handle exceptions using ControllerAdvice.
Code
@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(),
ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<ErrorDetails> handleUserNotFoundExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(),
ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.NOT_FOUND);
}
|
How to implement distributed logging for microservices?
|
-
Spring Cloud Sleuth is used to generate and attach the trace id, span id to the logs so that these can then be used by tools like Zipkin and ELK for storage and analysis
-
Zipkin ?? is a distributed tracing system. It helps gather timing data needed to troubleshoot latency problems in service architectures. Features include both the collection and lookup of this data.
|
Preventing cross-site request forgery CSRF.
|
Spring Security has built-in CSRF protection enabled by default.
- any forms your application submits should include a field named _csrf
- could be added in ThymeLeaf as <input type="hidden" name="_csrf" th:value="${_csrf.token}"/>
- sometimes could be added automatically
|
Template Engines
|
FreeMaker, ThymeLeaf
|