Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

A 5 Hour Video Course

Spring
Covers 200+ Interview Questions about
Spring
Spring MVC

Interview Questions Spring Boot


JPA, Sprint Data, Spring Data JPA
Spring Web Services
Spring REST

Find more about this at


http://www.in28minutes.com
Questions
Tight Coupling
What is loose coupling?
What is a Dependency? public class TodoBusinessService {

What is IOC (Inversion of Control)? TodoDataServiceImpl dataService = new TodoDataServiceImpl();


What is Dependency Injection? public class ComplexAlgorithmImpl {
Can you give few examples of Dependency
BubbleSortAlgorithm bubbleSortAlgorithm
Injection? = new BubbleSortAlgorithm();
What is Auto Wiring?
Loose Coupling Loose Coupling
@Component @Component
public class TodoBusinessService { public class ComplexAlgorithmImpl {

@Autowired @Autowired
TodoDataService dataService;// = new TodoDataService() private SortAlgorithm sortAlgorithm;

public TodoBusinessService(TodoDataService dataService) { public interface SortAlgorithm {


this.dataService = dataService; public int[] sort(int[] numbers);
} }

public interface TodoDataService { public class QuickSortAlgorithm implements SortAlgorithm {


List<String> retrieveTodos(String user);
} public class BubbleSortAlgorithm implements SortAlgorithm {

Dependency Injection
We use Spring Framework to instantiate beans and
Inversion of Control
wire dependencies public class ComplexAlgorithmImpl {

ComplexAlgorithmImpl binarySearch = BubbleSortAlgorithm bubbleSortAlgorithm


new ComplexAlgorithmImpl(new QuickSortAlgorithm()); = new BubbleSortAlgorithm();

@Component
@Component public class ComplexAlgorithmImpl {
public class ComplexAlgorithmImpl {
@Autowired
@Autowired private SortAlgorithm sortAlgorithm;
private SortAlgorithm sortAlgorithm;
Questions
What are the important roles of an IOC Container?
What are Bean Factory and Application Context?
Can you compare Bean Factory with Application
Context?
How do you create an application context with
Spring?

IOC Container
IOC Container
@Component
public class ComplexAlgorithmImpl {

@Autowired
Find Beans private SortAlgorithm sortAlgorithm;
Wire Dependencies @Component
Manage Lifecycle of the Bean public class QuickSortAlgorithm implements SortAlgorithm {

public interface SortAlgorithm {


public int[] sort(int[] numbers);
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"

Application Context xmlns:aop="http://www.springframework.org/schema/aop"


xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.spr
Bean Factory++ http://www.springframework.org/schema/tx http://www.spr
Spring’s AOP features http://www.springframework.org/schema/context http://ww
http://www.springframework.org/schema/aop http://www.sp
I18n capabilities </beans>
WebApplicationContext for web applications etc ApplicationContext context =
new ClassPathXmlApplicationContext(
new String[] {"BusinessApplicationContext.xml",
"Other-Configuration.xml"});

@Configuration
Unit Tests
class SpringContext {
@RunWith(SpringJUnit4ClassRunner.class)
}
@ContextConfiguration(classes = JavaTestContext.class)
public class DependencyInjectionJavaContextExamples {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(
@RunWith(SpringJUnit4ClassRunner.class)
SpringContext.class);
@ContextConfiguration(locations = { "/TestContext.xml" })
public class TodoBusinessTest {
Questions
How does Spring know where to search for Java Configuration
Components or Beans? @Configuration
What is a component scan? @ComponentScan(basePackages = {
"com.in28minutes.spring.example1.businessservice",
How do you define a component scan in XML and "com.in28minutes.spring.example1.dataservice.stub" })
Java Configurations? class SpringContext {
}
How is it done with Spring Boot?

XML Configuration Spring Boot


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" package com.in28minutes.spring.basics.springin5steps;
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" @SpringBootApplication
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" public class SpringIn5StepsApplication {
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
package com.in28minutes.spring.basics.springin5steps;
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
@RunWith(SpringRunner.class)
<context:component-scan @SpringBootTest
base-package="com.in28minutes.example"/> public class SpringIn5StepsApplicationTests {
</beans>
Questions
What does @Component signify? Notes
What does @Autowired signify? @Component - Spring should manage the bean.
What’s the difference Between @Controller, @Autowired - Spring should find the matching bean
@Component, @Repository, and @Service and wire the dependency in.
Annotations in Spring?

@Component
public class ComplexAlgorithmImpl { Notes
@Autowired
private SortAlgorithm sortAlgorithm;
@Component - Generic Component
@Repository - encapsulating storage, retrieval, and
public interface SortAlgorithm {
public int[] sort(int[] numbers);
search behavior typically from a relational database
} @Service - Business Service Facade
@Component
@Controller - Controller in MVC pattern
public class QuickSortAlgorithm implements SortAlgorithm {
Questions
What is the default scope of a bean?
Are Spring beans thread safe?
What are the other scopes available?
How is Spring’s singleton bean different from Gang
of Four Singleton Pattern?

Notes Other Scopes


singleton - One instance per Spring Context
The singleton scope is the default scope in Spring. prototype - New bean whenever requested
The Gang of Four defines Singleton as having one request - One bean per HTTP request. Web-aware
and only one instance per ClassLoader. Spring ApplicationContext.
However, Spring singleton is defined as one instance session - One bean per HTTP session. Web-aware
of bean definition per container. Spring ApplicationContext.
Examples Questions
@RequestScope
@Component What are the different types of dependency
public class RequestScopedBean {
injections?
@SessionScope What is setter injection?
@Component
public class SessionScopedBean {
What is constructor injection?
How do you choose between setter and constructor
<bean id="someBean" class="com.in28minutes.SomeBean"
scope="prototype"/>
injections?

Setter Injection
@Component
public class TodoBusinessService { Constructor Injection
TodoDataService dataService;
@Component
public class TodoBusinessService {
@Autowired
public void setDataService
TodoDataService dataService;
(TodoDataService dataService) {
this.dataService = dataService;
@Autowired
}
public TodoBusinessService(TodoDataService dataService) {
super();
//Through Reflection
this.dataService = dataService;
@Component
}
public class TodoBusinessService {

@Autowired
TodoDataService dataService;
Constructor vs Setter Injection Constructor vs Setter Injection
https://docs.spring.io/spring/docs/current/spring-
framework-reference/htmlsingle/ Furthermore constructor-injected components are
The Spring team generally advocates constructor always returned to client (calling) code in a fully
injection as it enables one to implement application initialized state.
components as immutable objects and to ensure As a side note, a large number of constructor
that required dependencies are not null. arguments is a bad code smell.

Questions
What are the different options available to create
Constructor vs Setter Injection Application Contexts for Spring?
What is the difference between XML and Java
Constructor Injection for Mandatory Dependencies Configurations for Spring?
Setter Injection for Optional Dependencies How do you choose between XML and Java
Configurations for Spring?
XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" Java
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" @Configuration
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
class SpringContext {
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
}
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
ApplicationContext ctx =
</beans> new AnnotationConfigApplicationContext(
SpringContext.class);
ApplicationContext context =
new ClassPathXmlApplicationContext(
new String[] {"BusinessApplicationContext.xml",
"Other-Configuration.xml"});

XML vs Java Configuration XML vs Java Configuration


Today, with use of annotations, the things that are With Spring Boot, we are slowly moving towards
specified in a Application Context are at bare complete Java Configuration.
minimum. package com.in28minutes.spring.basics.springin5steps;
There is little to choose between these as long as
@SpringBootApplication
the configuration is at a bare minimum. public class SpringIn5StepsApplication {
Questions Autowiring
byType
How does Spring do Autowiring? byName
What are the different kinds of matching used by constructor - similar to byType, but through
Spring for Autowiring? constuctor

by Name
by Type - Class or Interface @Component
public class ComplexAlgorithmImpl {
@Component
public class ComplexAlgorithmImpl {
@Autowired
private SortAlgorithm quickSortAlgorithm;
@Autowired
private SortAlgorithm sortAlgorithm;
public interface SortAlgorithm {
public int[] sort(int[] numbers);
public interface SortAlgorithm {
}
public int[] sort(int[] numbers);
}
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
@Component
public class BubbleSortAlgorithm implements SortAlgorithm {
No matching Components
Questions @Component
public class ComplexAlgorithmImpl {
How do you debug problems with Spring @Autowired
Framework? private SortAlgorithm sortAlgorithm;
NoUniqueBeanDefinitionException public interface SortAlgorithm {
NoSuchBeanDefinitionException public int[] sort(int[] numbers);
}
What is @Primary?
What is @Qualifier? public class QuickSortAlgorithm implements SortAlgorithm {

public class BubbleSortAlgorithm implements SortAlgorithm {

UnsatisfiedDependencyException:
Error creating bean with name 'binarySearchImpl':
Unsatisfied dependency expressed through field 'sortAlgorithm';
nested exception is org.springframework.beans.factory.:
No qualifying bean of type
Typically problems
'com.in28minutes.spring.basics.springin5steps.SortAlgorithm'
available: @Component missing
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations:
or @ComponentScan not defined properly
{@org.springframework.beans.factory.annotation.Autowired
(required=true)}
Exception - Two matching
Components
@Component
Field sortAlgorithm in
public class ComplexAlgorithmImpl {
springin5steps.BinarySearchImpl required a single
@Autowired
private SortAlgorithm sortAlgorithm;
bean, but 2 were found:
public interface SortAlgorithm { bubbleSortAlgorithm: defined in file
}
public int[] sort(int[] numbers); [BubbleSortAlgorithm.class]
quickSortAlgorithm: defined in file
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
[QuickSortAlgorithm.class]
@Component
public class BubbleSortAlgorithm implements SortAlgorithm {

Qualifier
Primary @Component
public class ComplexAlgorithmImpl {

@Autowired
@Component
@Qualifier("mainAlgorithm")
@Primary
private SortAlgorithm sortAlgorithm;
public class BubbleSortAlgorithm implements SortAlgorithm {
@Component
@Qualifier("mainAlgorithm")
public class BubbleSortAlgorithm implements SortAlgorithm {
Questions CDI
Java EE Dependency Injection Standard (JSR-330)
What is CDI (Contexts and Dependency Injection)? Spring Supports most annotations
Does Spring Support CDI? @Inject (@Autowired)
Would you recommed to use CDI or Spring @Named (@Component & @Qualifier)
Annotations? @Singleton (Defines a scope of Singleton)

Questions Notes
What are the major features in different versions of Spring 2.5 made annotation-driven configuration
Spring? possible.
What are new features in Spring Framework 4.0? Spring 3.0 made great use of the Java 5
What are new features in Spring Framework 5.0? improvements in language.
Spring 4.0 Spring 5.0
First version to fully support Java 8 features. Functional web framework
Minimum version of Java to use Spring 4 is Java SE Support for Jigsaw (Java Modularity)
6. Support for reactive programming
Introduced @RestController annotation Support for Kotlin
Spring 4.1 supports JCache (JSR-107) annotations

Spring Modules

Questions
What are important Spring Modules?
Questions
What are important Spring Projects?

Spring Projects
Spring Boot
Spring Cloud
Spring Data
Spring Integration Questions
Spring Batch
Spring Security What is the simplest way of ensuring that we are
Spring HATEOAS using single version of all Spring related
Spring Web Services dependencies?
Spring Session
Use a BOM
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>5.0.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Questions
</dependencies>
</dependencyManagement> Name some of the design patterns used in Spring
<dependencies>
Framework?
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependencies>

Design Patterns in Spring


Front Controller - Dispatcher Servlet
Prototype - Beans Questions
Dependency Injection
Factory Pattern - Bean Factory & Application Context What are some of the important Spring annotations
Template Method you have used?
org.springframework.web.servlet.mvc.AbstractController
Annotations
@Component, @Service, @Repository, @Controller Questions
@Autowired What do you think about Spring Framework?
@Primary Why is Spring Popular?
@Qualifier Can you give a big picture of the Spring Framework?
@Configuration

Architecture - Flexible & No Restrictions


Design - Loosely Coupled
Code - Easy Unit Testing
Features - Dependency Injection, IOC
Container(Bean Factory & Application Context), Auto
wiring, Component Scan
Spring Modules
MVC
Spring Projects
Questions
What is Model 1 architecture?

Questions
What is Model 2 architecture?
Questions
What is Model 2 Front Controller architecture?

Questions
Can you show an example controller method in Controller Method
Spring MVC?
Can you explain a simple flow in Spring MVC? @RequestMapping(value = "/list-todos",
method = RequestMethod.GET)
What is a ViewResolver? public String listTodos(ModelMap model) {
model.addAttribute("todos",
What is Model? service.retrieveTodos(retrieveLoggedinUserName()));
What is ModelAndView? return "list-todos";
}
What is a RequestMapping?
ViewResolver
<bean
class=
"org.springframework.web.servlet.view.InternalResourceViewResolver
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

Model vs ModelAndView
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showLoginPage(ModelMap model) {
model.put("name", "in28Minutes");
return "welcome";
Questions
}
What is Dispatcher Servlet?
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView showLoginPage() {
How do you set up Dispatcher Servlet?
ModelAndView mv = new ModelAndView();
mv.addObject("name", "in28Minutes");
mv.setViewName("welcome");
}
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet Questions
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/todo-servlet.xml</param-value>
What is a form backing object?
</init-param> How is validation done using Spring MVC?
<load-on-startup>1</load-on-startup>
</servlet>
What is BindingResult?
How do you map validation results to your view?
<servlet-mapping>
<servlet-name>dispatcher</servlet-name> What are Spring Form Tags?
<url-pattern>/</url-pattern>
</servlet-mapping>

todo.jsp
Show New Todo Page <form:form method="post" commandName="todo">
<fieldset>
@RequestMapping(value = "/add-todo",
<form:label path="desc">Description</form:label>
method = RequestMethod.GET)
<form:input path="desc" type="text"/>
public String showTodoPage(ModelMap model) {
<form:errors path="desc"/>
</fieldset>
model.addAttribute("todo", new Todo(0,
<fieldset>
retrieveLoggedinUserName(), "",
<form:label path="targetDate">Target Date</form:label>
new Date(), false));
<form:input path="targetDate" type="text" />
return "todo";
<form:errors path="targetDate"/>
</fieldset>
}
<input type="submit" value="Submit" />
</form:form>
Add Todo
@RequestMapping(value = "/add-todo", method = RequestMethod.POST)
Todo.java
public String addTodo(ModelMap model, @Valid Todo todo,
BindingResult result) { public class Todo {
if (result.hasErrors()) {
return "todo"; private int id;
} private String user;
service.addTodo(retrieveLoggedinUserName(), todo.getDesc(), new
false); @Size(min = 6, message = "Enter atleast 6 characters")
model.clear(); private String desc;
return "redirect:list-todos";
}

Questions Path Variable


http://localhost:8080/todos/1
What is a Path Variable?
What is a Model Attribute? @RequestMapping(value = "/todos/{id}")
public Todo retrieveTodo(@PathVariable int id) {
What is a Session Attribute? return service.retrieveTodo(id);
}
Model Attribute
@ModelAttribute
Indicates the purpose of that method is to add one
public void addAttributes(Model model) { or more model attributes.
model.addAttribute("options",
Arrays.asList(
Invoked before @RequestMapping methods.
"Option 1","Option 2","Option 3" )); Used to fill the model with commonly needed
}
attributes
Drop down values for form

@SessionAttributes
List the names of model attributes which should be Questions
transparently stored in the session or some
conversational storage. What is a init binder?
@SessionAttributes("name")
How do you set default date format with Spring?
public class TodoController {
Questions
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"
How do you implement common logic for
binder.registerCustomEditor(Date.class, new CustomDateEditor( Controllers in Spring MVC?
}
dateFormat, false));
What is a Controller Advice?
What is @ExceptionHandler?

ExceptionController
Questions @ControllerAdvice
public class ExceptionController {

How to handle exceptions for web applications? private Log logger = LogFactory.getLog(ExceptionController.class);
What are the important things to think about when @ExceptionHandler(value = Exception.class)
implementing Exception Handling? public String handleException
(HttpServletRequest request, Exception ex) {
How do you implement Specific Error Handling for a logger.error("Request " + request.getRequestURL()
Spring MVC Controller? + " Threw an Exception", ex);
return "error";
}

}
Spring MVC
Clear Seperation of Concerns
Questions Dispatcher Servlet
View Resolver
Why is Spring MVC so popular? View
Model

We will discuss more "Spring


MVC" questions in the section on Spring Boot
RESTful Webservices.
Why Spring Boot?
Questions Spring based applications have a lot of
What is Spring Boot? configuration.
What are the important Goals of Spring Boot? When we use Spring MVC, we need to configure
What are the important Features of Spring Boot? component scan, dispatcher servlet, a view resolver,
web jars(for delivering static content) among other
things.

Why Spring Boot? Spring Boot Goals


Quick Start to Spring
World is moving towards Microservices. Be opinionated
We do not have a lot of time to set up 100 Non functional features
microservices. No code generation
Spring Boot Features
Auto Configuration Questions
Spring Boot Starter Projects Compare Spring Boot vs Spring?
Spring Boot Actuator Compare Spring Boot vs Spring MVC?
Embedded Server

Spring
@RestController
public class WelcomeController {
Most important feature of Spring
private WelcomeService service = new WelcomeService();
Framework is Dependency Injection. At
@RequestMapping("/welcome")
the core of all Spring Modules is public String welcome() {
return service.retrieveWelcomeMessage();
Dependency Injection or IOC Inversion }
}
of Control.
With Spring
@Component
public class WelcomeService {
//Bla Bla Bla
}
Problems Spring Solves
@RestController
public class WelcomeController { Problem 1 : Duplication/Plumbing Code
@Autowired Problem 2 : Good Integration with Other
private WelcomeService service; Frameworks.
@RequestMapping("/welcome")
public String welcome() {
return service.retrieveWelcomeMessage();
}
}

Spring MVC Spring Boot


Eliminates all configuration needed by Spring and
Spring MVC Framework provides Spring MVC and auto configures it
decoupled way of developing web No need for @ComponentScan. Default
applications. With simple concepts like Component Scan.
Dispatcher Servlet, ModelAndView and No need to configure DispatcherServlet
No need to configure a Data Source, Entity
View Resolver, it makes it easy to Manager Factory or Transaction Manager.
develop web applications.
Spring Boot Thinking
Spring Boot Thinking Spring Boot looks at
Can we bring more intelligence into Frameworks available on the CLASSPATH
this? When a spring mvc jar is added Existing configuration for the application.
into an application, can we auto
Based on these, Spring Boot provides
configure some beans automatically?
Auto Configuration.

SpringBootApplication
Questions @SpringBootConfiguration
@EnableAutoConfiguration
What is the importance of @SpringBootApplication? @ComponentScan
public @interface SpringBootApplication {
Spring Boot looks at a) Frameworks
Questions available on the CLASSPATH b) Existing
configuration for the application.
What is Auto Configuration? Based on these, Spring Boot provides
How can we find more information about Auto
Configuration? basic configuration needed to
configure the application with these
frameworks. This is called Auto
Configuration.

Implementation
Application Startup Log
spring-boot-autoconfigure.jar
Mapping servlet: 'dispatcherServlet' to [/] To get more details
Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity Turn on Debug logging
logging.level.org.springframework:
<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.
BasicErrorController.error(javax.servlet.http.HttpServletRequest)
DEBUG
Mapped URL path [/webjars/ * *] onto handler of type
[class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] Use Spring Boot Actuator
Questions Embedded Server
What is an embedded server? Why is it important? Server is embedded as part of the deployable - jar.
What is the default embedded server with Spring Removes the need to have the server pre-installed
Boot? on the deployment environment.
What are the other embedded servers supported by Default is Tomcat.
Spring Boot? Spring Boot also supports Jetty and UnderTow.

Switching to Jetty
<dependency>
<groupId>org.springframework.boot</groupId>

Questions
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId> What are Starter Projects?
</exclusion>
</exclusions> Can you give examples of important starter
</dependency>
<dependency>
projects?
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Spring Boot Documentation
Starters are a set of convenient
Spring Boot Documentation
dependency descriptors that you can
For example, if you want to get started
include in your application. You get a
using Spring and JPA for database
one-stop-shop for all the Spring and
access, just include the spring-boot-
related technology that you need,
starter-data-jpa dependency in your
without having to hunt through sample
project, and you are good to go.
code and copy paste loads of
dependency descriptors.

Starters
Starters spring-boot-starter-security - Authentication and
Authorization using Spring Security
spring-boot-starter-web-services - SOAP spring-boot-starter-data-jpa - Spring Data JPA with
WebServices Hibernate
spring-boot-starter-web - Web & RESTful spring-boot-starter-cache - Enabling Spring
applications Framework’s caching support
spring-boot-starter-test - Unit, Integration Testing spring-boot-starter-data-rest - Expose Simple REST
spring-boot-starter-jdbc - Traditional JDBC Services using Spring Data REST
spring-boot-starter-hateoas - HATEOAS features
spring-boot-starter-actuator - To use advanced
features like monitoring & tracing to your
application out of the box Questions
spring-boot-starter-undertow, spring-boot-starter-
jetty, spring-boot-starter-tomcat - To pick your What is Starter Parent?
specific choice of Embedded Servlet Container What are the different things that are defined in
spring-boot-starter-logging - For Logging using Starter Parent?
logback How does Spring Boot enforce common
spring-boot-starter-log4j2 - Logging using Log4j2 dependency management for all its Starter projects?

Inside Starter Parent


<parent>
Starter Parent <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.0.RELEASE</version>
<parent> <relativePath>../../spring-boot-dependencies</relativePath>
<groupId>org.springframework.boot</groupId> </parent>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version> <java.version>1.6</java.version>
</parent> <resource.delimiter>@</resource.delimiter> <!-- delimiter that doesn't clash wit
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
Inside Spring Boot Dependencies
<ehcache3.version>3.1.1</ehcache3.version>
...
<h2.version>1.4.192</h2.version>
<hamcrest.version>1.3</hamcrest.version>
<hazelcast.version>3.6.4</hazelcast.version> Questions
<hibernate.version>5.0.9.Final</hibernate.version>
<hibernate-validator.version>5.2.4.Final</hibernate-validator.version
<jackson.version>2.8.1</jackson.version>
What is Spring Initializr?
....
<jersey.version>2.23.1</jersey.version>
<spring-security.version>4.1.1.RELEASE</spring-security.version>
<tomcat.version>8.5.4</tomcat.version>
<xml-apis.version>1.4.01</xml-apis.version>

Spring Initializr http://start.spring.io/ is


Questions
great tool to bootstrap your Spring What is application.properties?
What are some of the important things that can
Boot projects. customized in application.properties?
Example Configuration
logging.file=
application.properties is used to logging.level.*=
spring.autoconfigure.exclude=
configure your Spring Boot Application spring.profiles.active=
server.error.path=/error
server.port=8080
spring.http.converters.preferred-json-mapper=jackson

Questions
How do you externalize configuration using Spring logging:
level:
Boot? org.springframework: DEBUG
How can you add custom application properties app:
name: In28Minutes
using Spring Boot? description: ${app.name} is your first Spring Boot application
What is @ConfigurationProperties?
@Autowired
private BasicConfiguration configuration;
import
org.springframework.boot.context.properties.ConfigurationProperties;
@RequestMapping("/dynamic-configuration")
public Map dynamicConfiguration() {
@Component
// Not the best practice to use a map to store differnt types!
@ConfigurationProperties("basic")
Map map = new HashMap();
public class BasicConfiguration {
map.put("message", configuration.getMessage());
private boolean value;
map.put("number", configuration.getNumber());
private String message;
map.put("key", configuration.isValue());
private int number;
return map;
}

Advantage
application.properties Type Safety
***************************
basic.value= true APPLICATION FAILED TO START
basic.message= Dynamic Message ***************************
basic.number= 100
Description:
application.yaml Binding to target
com.in28minutes.springboot.configuration.BasicConfiguration@391b8545
basic: failed:
value: true
message: Dynamic Message YAML Property: basic.number
number: 100 Value: ABC
Reason: Failed to convert property value of type [java.lang.String]
to required type [int] for property 'number'; nested exception is
org.springframework.core.convert.ConverterNotFoundException:
No converter found capable of converting from
Questions
Good Practice What is a profile?
Design all your application configuration using How do you define beans for a specific profile?
ConfigurationProperties How do you create application configuration for a
specific profile?

Profile
Profile application-dev.properties
application-qa.properties
How do you have different application-stage.properties
configuration for different application-prod.properties
environments? application.properties
Profile
Based on the active profile, appropriate Setting a profile
configuration is picked up. Using -Dspring.profiles.active=prod in VM
Used to Configure Resources - Databases, Queues, Arguments
External Services In application.properties,
spring.profiles.active=prod

Profiles in code
@Profile("dev") on a bean Questions
@Profile("dev") What is Spring Boot Actuator?
@Bean
public String devBean() {
How do you monitor web services using Spring Boot
return "I will be available in profile dev"; Actuator?
}
How do you find more information about your
@Profile("prod") application envrionment using Spring Boot?
@Bean
public String prodBean() {
return "I will be available in profile prod";
}
Spring Boot Actuator
Monitoring
/env, /metrics, /trace, /dump
/beans, / autoconfig, /configprops, /mappings Questions
URL has changed in Spring Boot 2.0 - /application
<dependency>
What is a CommandLineRunner?
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

CommandLineRunner
Spring Documentation - interface used
to indicate that a bean should run
Database Connectivity - JDBC,
when it is contained within a Spring JDBC & JPA
SpringApplication

public interface CommandLineRunner {


void run(String... args) throws Exception;
}
JDBC - Update Todo
Connection connection = datasource.getConnection();

Questions PreparedStatement st = connection.prepareStatement(


"Update todo set user=?, desc=?, target_date=?, is_done=? where id=?"

What is Spring JDBC? How is different from JDBC? st.setString(1, todo.getUser());


What is a JdbcTemplate? st.setString(2, todo.getDesc());
st.setTimestamp(3, new Timestamp(todo.getTargetDate().getTime()));
What is a RowMapper? st.setBoolean(4, todo.isDone());
st.setInt(5, todo.getId());

st.execute();
st.close();
connection.close();

Spring JDBC - RowMapper


new BeanPropertyRowMapper(Todo.class)
Spring JDBC class TodoMapper implements RowMapper<Todo> {
@Override
jdbcTemplate public Todo mapRow(ResultSet rs, int rowNum)
.update throws SQLException {
("Update todo set user=?, desc=?, target_date=?, is_done=? where id=?" Todo todo = new Todo();
todo.getUser(), todo.getDesc(),
new Timestamp(todo.getTargetDate().getTime()), todo.setId(rs.getInt("id"));
todo.isDone(), todo.getId()); todo.setUser(rs.getString("user"));
todo.setDesc(rs.getString("desc"));
jdbcTemplate.update("delete from todo where id=?", todo.setTargetDate(
id); rs.getTimestamp("target_date"));
todo.setDone(rs.getBoolean("is_done"));
return todo;
}
}
Spring JDBC - RowMapper Questions
return jdbcTemplate.query(
What is JPA?
"SELECT * FROM TODO where user = ?", What is Hibernate?
new Object[] { user }, new TodoMapper());
How do you define an entity in JPA?
return jdbcTemplate.queryForObject( What is an Entity Manager?
"SELECT * FROM TODO where id=?",
new Object[] { id }, new TodoMapper())
What is a Persistence Context?

JPA - Update Todo


Defining an entity
@Entity
JPA - Update Todo
@Table(name = "Todo")
public class TodoJPAService implements TodoDataService {
public class Todo {
@PersistenceContext
@Id
private EntityManager entityManager;
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Override
public void updateTodo(Todo todo) {
private String user;
entityManager.merge(todo);
}
private String desc;

private Date targetDate;

private boolean isDone;


One to One Relationship

Questions
@Entity
public class Passport {

....
// Inverse Relationship
// bi-directional OneToOne relationship
How do you map relationships in JPA? // Column will not be created in the table
What are the different types of relationships in JPA? // Try removing mappedBy = "passport" => You will see that student_id column
// will be created in passport
How do you define One to One Mapping in JPA? @OneToOne(fetch = FetchType.LAZY, mappedBy = "passport")
How do you define One to Many Mapping in JPA? private Student student;

How do you define Many to Many Mapping in JPA? @Entity


@Table(name = "Student")
public class Student {

@OneToOne
private Passport passport;

One to Many Relationship Many to Many Relationship


@Entity
@Entity public class Project {
public class Project {
@OneToMany(mappedBy = "project") @ManyToMany
private List<Task> tasks; // @JoinTable(name="STUDENT_PROJ",
// joinColumns=@JoinColumn(name="STUDENT_ID"),
@Entity // inverseJoinColumns=@JoinColumn(name="PROJECT_ID"))
public class Task { private List<Student> students;
@ManyToOne
@JoinColumn(name="PROJECT_ID") public class Student {
private Project project; @ManyToMany(mappedBy = "students")
private List<Project> projects;
Questions Defining a Data Source
#HSQL in-memory db
How do you define a datasource in a Spring db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:firstdb
Context? db.username=sa
db.password=
What is the use of persistence.xml
How do you configure Entity Manager Factory and <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
Transaction Manager? <property name="driverClass" value="${db.driver}" />
How do you define transaction management for <property name="jdbcUrl" value="${db.url}" />
<property name="user" value="${db.username}" />
Spring – Hibernate integration? <property name="password" value="${db.password}" />
</bean>

persistence.xml
src\main\resources\META-INF\persistence.xml
Configuring Hibernate <?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
src\main\resources\config\hibernate.properties version="2.0">
<persistence-unit name="hsql_pu" transaction-type="RESOURCE_LOCAL"
hibernate.dialect=org.hibernate.dialect.HSQLDialect <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider
hibernate.show_sql=false <properties>
hibernate.format_sql=false <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialec
hibernate.use_sql_comments=true <property name="hibernate.connection.url" value="jdbc:hsqldb:mem:firstdb"
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcD
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
</properties>
</persistence-unit>
</persistence>
Configure Entity Manager Making Service Transactional
Factory and Transaction @Service
public class StudentService {

Manager @Autowired
StudentRepository service;

@Transactional
<bean
public Student insertStudent(Student student) {
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
return service.insertStudent(student);
id="entityManagerFactory">
}
<property name="persistenceUnitName" value="hsql_pu" />
<property name="dataSource" ref="dataSource" />
</bean> @Service
@Transactional
public class StudentService {
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
<property name="entityManagerFactory" ref="entityManagerFactory"
<property name="dataSource" ref="dataSource" /> @Autowired
</bean> StudentRepository service;

<tx:annotation-driven transaction-manager="transactionManager"

Questions
Spring Data What is Spring Data?
What is the need for Spring Data?
What is Spring Data JPA?
Duplication in JPA Repositories Duplication in JPA Repositories
Passport Repository
Student Repository
@PersistenceContext
private EntityManager entityManager; @PersistenceContext
private EntityManager entityManager;
public Passport getPassport(final long id) {
Passport passport = entityManager public Student retrieveStudent(final long id) {
.find(Passport.class, id); return entityManager.find(Student.class, id);
return passport; }
}
public Student createStudent(Student student) {
public Passport createPassport(Passport passport) { return entityManager.merge(student);
return entityManager.merge(passport); }
}

Spring Data
Explosion of Data Stores Common Abstractions to store and
Variety of Big Data Stores retrieve data from data stores
Independent of type of data store
Spring Data JPA Using Spring Data JPA
public interface StudentRepository extends CrudRepository<Student
Extends Spring Data for connecting to }

JPA public interface PassportRepository extends CrudRepository<Passport


}

CrudRepository
Questions public interface CrudRepository<T, ID> extends Repository<T, ID>
<S extends T> S save(S entity);
Optional<T> findById(ID id);
boolean existsById(ID id);
What is a CrudRepository? Iterable<T> findAll();
void deleteById(ID id);
What is a PagingAndSortingRepository? long count();
//Other Methods
}
Using
PagingAndSortingRepository
PagingAndSortingRepository
Pagination and Sorting Sort sort = new Sort(Sort.Direction.DESC,"field_name");
passportRepository.findAll(sort);
public interface PagingAndSortingRepository<T, ID>
extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort); //Page Size - 10
Page<T> findAll(Pageable pageable); PageRequest pageable = new PageRequest(0,10);
} Page<Passport> page = passportRepository.findAll(pageable);
System.out.println(userPage.getTotalPages());
System.out.println(userPage.nextPageable());

Questions
How does Spring Framework Make Unit Testing

Unit Testing
Easy?
What is Mockito?
What is your favorite mocking framework?
How do you do mock data with Mockito?
What are the different mocking annotations that you
worked with?
public class SomeBusinessImpl {
Basic Mocking
private DataService dataService;
//Constructor - public SomeBusinessImpl(DataService dataService) @Test
int findTheGreatestFromAllData() { public void testFindTheGreatestFromAllData() {
int[] data = dataService.retrieveAllData();
int greatest = Integer.MIN_VALUE; DataService dataServiceMock = mock(DataService.class);
when(dataServiceMock.retrieveAllData())
for (int value : data) { .thenReturn(new int[] { 24, 15, 3 });
if (value > greatest) {
greatest = value; SomeBusinessImpl businessImpl =
} new SomeBusinessImpl(dataServiceMock);
}
return greatest; int result = businessImpl.findTheGreatestFromAllData();
}
} assertEquals(24, result);
}

Using Annotations
@RunWith(MockitoJUnitRunner.class)
public class SomeBusinessMockAnnotationsTest { Questions
@Mock
DataService dataServiceMock; What is MockMvc?
@InjectMocks What is @WebMvcTest?
SomeBusinessImpl businessImpl; What is @MockBean?
@Test How do you write a unit test with MockMVC?
public void testFindTheGreatestFromAllData() {
when(dataServiceMock.retrieveAllData())
What is JSONAssert?
.thenReturn(new int[] { 24, 15, 3 });
assertEquals(24, businessImpl.findTheGreatestFromAllData());
}
Mock MVC Test with Spring Boot
Mock MVC Test with Spring Boot @RunWith(SpringRunner.class)
@WebMvcTest(value = SurveyController.class, secure = false)
public Question retrieveDetailsForQuestion(
public class SurveyControllerTest {
@PathVariable String surveyId,
@PathVariable String questionId) {
@Autowired
return
private MockMvc mockMvc;
surveyService.retrieveQuestion(surveyId, questionId);
}
@MockBean
private SurveyService surveyService;

Mock MVC Test - Continued Mock MVC Test - Continued


@Test
public void retrieveDetailsForQuestion() throws Exception { MvcResult result = mockMvc.perform(requestBuilder)
Question mockQuestion = new Question("Question1", .andReturn();
"Largest Country in the World", "Russia", Arrays.asList(
"India", "Russia", "United States", "China")); String expected =
"{id:Question1,description:Largest Country in the World,correctAnswer:Russia
Mockito.when(
surveyService.retrieveQuestion(Mockito.anyString(), Mockito JSONAssert.assertEquals(expected, result.getResponse()
.anyString())).thenReturn(mockQuestion); .getContentAsString(), false);

RequestBuilder requestBuilder = MockMvcRequestBuilders.get( // Assert


"/surveys/Survey1/questions/Question1").accept( }
MediaType.APPLICATION_JSON);
Integration Test with Spring Boot
Questions @RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
How do you write an integration test with Spring webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SurveyControllerIT {
Boot?
What is @SpringBootTest? @LocalServerPort
private int port;
What is @LocalServerPort?
What is TestRestTemplate? }

Integration Test with Spring Boot


@Test
public void testRetrieveSurveyQuestion() {

String url = "http://localhost:" + port


Integration Test with Spring Boot
+ "/surveys/Survey1/questions/Question1";
String expected =
"{id:Question1,description:Largest Country in the World,correctAnswer:Russia}"
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
JSONAssert.assertEquals(expected, response.getBody(), false);
HttpEntity<String> entity =
}
new HttpEntity<String>(null, headers);

TestRestTemplate restTemplate = new TestRestTemplate();


ResponseEntity<String> response = restTemplate.exchange(url,
HttpMethod.GET, entity, String.class);
Questions
What are cross cutting concerns?
How do you implement cross cutting concerns in a

AOP web application?


If you would want to log every request to a web
application, what are the options you can think of?
If you would want to track performance of every
request, what options can you think of?

Questions
What is an Aspect and Pointcut in AOP?
What are the different types of AOP advices?
What is weaving?
@Component
class HiByeService {
public void sayHi(String name) {
@Aspect
System.out.println("Hi " + name);
@Component
}
class MyAspect {
@Before("execution(* HiByeService.*(..))")
public void sayBye() {
public void before(JoinPoint joinPoint) {
System.out.println("Bye");
System.out.print("Before ");
}
System.out.print(joinPoint.getSignature().getName());
System.out.println(Arrays.toString(joinPoint.getArgs()));
public String returnSomething() {
}
return "Hi Bye";
}
}

@Around(value = "execution(* HiByeService.*(..))")


@AfterReturning(pointcut = "execution(* HiByeService.*(..))" public void around(ProceedingJoinPoint joinPoint)
, returning = "result") throws Throwable {
public void after(JoinPoint joinPoint, Object result) { long startTime = new Date().getTime();
System.out.print("After "); Object result = joinPoint.proceed();
System.out.print(joinPoint.getSignature().getName()); long endTime = new Date().getTime();
System.out.println(" result is " + result); System.out.print("Execution Time - "
} + (endTime - startTime));
} }
AOP concepts Advice Types
Joinpoint
Advice Before advice
Pointcut A er returning advice
Aspect A er throwing advice
Weaving A er (finally) advice - Always executed
Weaver Around advice - Most powerful - Performance
Logging

AspectJ vs Spring AOP


AspectJ is a full fledged AOP framework
Advise objects not managed by the Spring container
Advise join points other than simple method
SOAP Web Services
executions
(for example, field get or set join points)
Questions
What is a Web Service?

3 Keys Questions
What is SOAP Web Service?
Designed for machine-to-machine (or application- What is SOAP?
to-application) interaction Waht is a SOAP Envelope?
Should be interoperable - Not platform dependent What is SOAP Header and SOAP Body?
Should allow communication over a network
This is Not SOAP Web Service This is SOAP Web Service

SOAP Envelope
SOAP
Format Questions
SOAP XML Request Can you give an example of SOAP Request and SOAP
SOAP XML Response Response?
Transport What is a SOAP Header? What kind of information is
SOAP over MQ sent in a SOAP Header?
SOAP over HTTP Can you give an example of a SOAP Header with
Service Definition Authentication information?
WSDL

SOAP Request SOAP Response


<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" <SOAP-ENV:Header/>
<SOAP-ENV:Header/> <SOAP-ENV:Body>
<SOAP-ENV:Body> <ns2:getCourseDetailsResponse xmlns:ns2="http://in28minutes.com/courses"
<ns2:GetCourseDetailsRequest xmlns:ns2="http://in28minutes.com/courses" <ns2:course>
<ns2:course> <ns2:id>1</ns2:id>
<ns2:id>1</ns2:id> <ns2:name>Spring</ns2:name>
</ns2:GetCourseDetailsRequest> <ns2:description>10 Steps</ns2:description>
</ns2:getCourseDetailsResponse> </ns2:course>
</SOAP-ENV:Body> </ns2:getCourseDetailsResponse>
</SOAP-ENV:Envelope> </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
SOAP Header
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
mustUnderstand="1">
Questions
<wsse:UsernameToken>
<wsse:Username>user</wsse:Username>
<wsse:Password>password</wsse:Password>
What is WSDL (Web Service Definition Language)?
</wsse:UsernameToken> What are the different parts of a WSDL?
</wsse:Security>
</Header>
<Body>
<GetCourseDetailsRequest xmlns="http://in28minutes.com/courses"
<id>1</id>
</GetCourseDetailsRequest>
</Body>

WSDL
Web Service Definition Language
Questions
What is Contract First Approach?
What is an XSD?
Can you give an example of an XSD?

Contract
Service Definition specifying
Contract First
Format of Request
Format of Response We define a contract first!
Request/Response Structure
Transport used With Spring Web Services, we define an XSD first
Endpoint details
XSD Request XML
XML Specification Document! <GetCourseDetailsRequest xmlns="http://in28minutes.com/courses">
<id>1</id>
How does a valid XML Look like? </GetCourseDetailsRequest>

XSD Response XML


<xs:element name="GetCourseDetailsRequest"> <ns2:GetCourseDetailsResponse xmlns:ns2="http://in28minutes.com/courses"
<xs:complexType> <ns2:CourseDetails>
<xs:sequence> <ns2:id>1</ns2:id>
<xs:element name="id" type="xs:int" /> <ns2:name>Spring</ns2:name>
</xs:sequence> <ns2:description>10 Steps</ns2:description>
</xs:complexType> </ns2:CourseDetails>
</xs:element> </ns2:GetCourseDetailsResponse>
XSD XSD
<xs:element name="GetCourseDetailsResponse"> <xs:complexType name="CourseDetails">
<xs:complexType> <xs:sequence>
<xs:sequence> <xs:element name="id" type="xs:int" />
<xs:element name="CourseDetails" type="tns:CourseDetails" /> <xs:element name="name" type="xs:string" />
</xs:sequence> <xs:element name="description" type="xs:string" />
</xs:complexType> </xs:sequence>
</xs:element> </xs:complexType>

Questions Convert from Java to SOAP XML


What is JAXB?
How do you configure a JAXB Plugin?
JAXB Plugin
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
Questions
<executions>
<execution>
<id>xjc</id>
What is an Endpoint?
<goals> Can you show an example endpoint written with
<goal>xjc</goal>
</goals>
Spring Web Services?
</execution>
</executions>
<configuration>
<schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory
<outputDirectory>${project.basedir}/src/main/java</outputDirectory
<clearOutputDir>false</clearOutputDir>

Endpoint
@PayloadRoot(namespace = "http://in28minutes.com/courses",
localPart = "GetCourseDetailsRequest")
@ResponsePayload
public GetCourseDetailsResponse processCourseDetailsRequest Questions
(@RequestPayload GetCourseDetailsRequest request) {

Course course = service.findById(request.getId());


What is a MessageDispatcherServlet?
How do you configure a MessageDispatcherServlet?
if (course == null)
throw new CourseNotFoundException("Invalid Course Id " + request.getId());

return mapCourseDetails(course);
}
MessageDispatcherServlet
@Bean
public ServletRegistrationBean messageDispatcherServlet
(ApplicationContext context) {
Questions
MessageDispatcherServlet messageDispatcherServlet
= new MessageDispatcherServlet(); How do you generate a WSDL using Spring Web
messageDispatcherServlet.setApplicationContext(context);
messageDispatcherServlet.setTransformWsdlLocations(true);
Services?
return new ServletRegistrationBean(messageDispatcherServlet,
"/ws/*");
}

@Bean(name = "courses")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema coursesSchema)
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName("CoursePort");
definition.setTargetNamespace("http://in28minutes.com/courses"
definition.setLocationUri("/ws");
Questions
definition.setSchema(coursesSchema);
return definition; How do you implement error handling for SOAP Web
} Services?
@Bean What is a SOAP Fault?
public XsdSchema coursesSchema() {
return new SimpleXsdSchema(
new ClassPathResource("course-details.xsd"));
}
Endpoint
@PayloadRoot(namespace = "http://in28minutes.com/courses",
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
localPart = "GetCourseDetailsRequest")
<SOAP-ENV:Header/>
@ResponsePayload
<SOAP-ENV:Body>
public GetCourseDetailsResponse processCourseDetailsRequest
<SOAP-ENV:Fault>
(@RequestPayload GetCourseDetailsRequest request) {
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring xml:lang="en">Invalid Course Id 1000</faultstring
Course course = service.findById(request.getId());
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
if (course == null)
</SOAP-ENV:Envelope>
throw new CourseNotFoundException("Invalid Course Id " + request.getId());

return mapCourseDetails(course);
}

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
<SOAP-ENV:Header />
@SoapFault( <SOAP-ENV:Body>
faultCode = FaultCode.CUSTOM, <SOAP-ENV:Fault>
customFaultCode = <faultcode xmlns:ns0="http://in28minutes.com/courses">
"{http://in28minutes.com/courses}001_COURSE_NOT_FOUND" ns0:001_COURSE_NOT_FOUND</faultcode>
) <faultstring xml:lang="en">
public class CourseNotFoundException extends RuntimeException { Invalid Course Id 1234</faultstring>
} </SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Questions
RESTful Web What is REST?

Services

REST is a style of so ware architecture


REpresentational State Transfer
for distributed hypermedia systems
Make best use of HTTP
Key abstraction - Resource
A resource has an URI (Uniform Resource Identifier)
/users/Ranga/todos/1
/users/Ranga/todos
/users/Ranga

REST
Example Data Exchange Format
Create a User - POST /users No Restriction. JSON is popular
Delete a User - DELETE /users/1 Transport
Get all Users - GET /users Only HTTP
Get one Users - GET /users/1 Service Definition
No Standard. WADL/Swagger/...
Questions Best Practices in
What are the Best Practices of RESTful Services?
RESTful Design

Make best use of


Consumer First
HTTP
Response Status
Request Methods 200 - SUCCESS
GET 404 - RESOURCE NOT FOUND
POST 400 - BAD REQUEST
PUT 201 - CREATED
DELETE 401 - UNAUTHORIZED
500 - SERVER ERROR

Use Plurals
No Secure Info in URI Prefer /users to /user
Prefer /users/1 to /user/1
Questions
Can you show the code for an example Get Resource
method with Spring REST? @GetMapping("/users")
What happens when we return a bean from a public List<User> retrieveAllUsers() {
return service.findAll();
Request Mapping Method? }
What is GetMapping and what are the related
methods available in Spring MVC?

@PostMapping("/users")
public ResponseEntity<Object> createUser(

Questions @Valid @RequestBody User user) {


User savedUser = service.save(user);

URI location = ServletUriComponentsBuilder


Can you show the code for an example Post .fromCurrentRequest()
Resource method with Spring REST? .path("/{id}")
.buildAndExpand(savedUser.getId()).toUri();
Why do we use ResponseEntity in a RESTful Service?
return ResponseEntity.created(location).build();

}
HATEOAS
Questions Hypermedia as The Engine of Application State
Example
What is HATEOAS? When requested for details of a facebook post, we
Can you give an Example Response for HATEOAS? return
How do we implement it using Spring? Link for actions to like, unlike or comment on
the post

{
"id": 1,
"name": "Adam",
"birthDate": "2017-07-19T09:26:18.337+0000", <dependency>
"_links": { <groupId>org.springframework.boot</groupId>
"all-users": { <artifactId>spring-boot-starter-hateoas</artifactId>
"href": "http://localhost:8080/users" </dependency>
}
}
}
@GetMapping("/users/{id}")
Questions
public Resource<User> retrieveUser
(@PathVariable int id) {
User user = service.findOne(id);
How do you document RESTful web services?
Can you give a brief idea about Swagger
Resource<User> resource = new Resource<User>(user); Documentation?
ControllerLinkBuilder linkTo = How do you automate generation of Swagger
linkTo(methodOn(this.getClass()).retrieveAllUsers());
Documentation from RESTful Web Services?
resource.add(linkTo.withRel("all-users")); How do you add custom information to Swagger
return resource;
Documentation generated from RESTful Web
} Services?
What is Swagger-UI?

OpenAPI Specification (formerly called the Swagger


Specification). <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
The specification creates the RESTful </dependency>
contract for your API, detailing all of its <dependency>
<groupId>io.springfox</groupId>
resources and operations in a human <artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
and machine readable format for easy </dependency>
development, discovery, and
integration.
public static final Contact DEFAULT_CONTACT = new Contact(
@Configuration "Ranga Karanam", "http://www.in28minutes.com", "in28minutes@gmail.com"
@EnableSwagger2
public class SwaggerConfig { public static final ApiInfo DEFAULT_API_INFO = new ApiInfo(
"Awesome API Title", "Awesome API Description", "1.0",
@Bean "urn:tos", DEFAULT_CONTACT,
public Docket api() { "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0");
return new Docket(DocumentationType.SWAGGER_2);
} private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES =
} new HashSet<String>(Arrays.asList("application/json",
"application/xml"));

Customizing
@Bean
public Docket api() { @ApiModel(description="All details about the user.")
return new Docket(DocumentationType.SWAGGER_2) @Entity
.apiInfo(DEFAULT_API_INFO) public class User {
.produces(DEFAULT_PRODUCES_AND_CONSUMES)
.consumes(DEFAULT_PRODUCES_AND_CONSUMES); @Size(min=2, message="Name should have atleast 2 characters")
} @ApiModelProperty(notes="Name should have atleast 2 characters"
private String name;
Questions
What is "Representation" of a Resource? A resource can have different representations
What is Content Negotiation? XML
Which HTTP Header is used for Content HTML
Negotiation? JSON
How do we implement it using Spring Boot?
How do you add XML support to your RESTful
Services built with Spring Boot?

GET http://localhost:8080/users
GET http://localhost:8080/users Accept application/xml
[
{ <List>
"id": 2, <item>
"name": "Eve", <id>2</id>
"birthDate": "2017-07-19T04:40:20.796+0000" <name>Eve</name>
}, <birthDate>2017-07-19T10:25:20.450+0000</birthDate>
{ </item>
"id": 3, <item>
"name": "Jack", <id>3</id>
"birthDate": "2017-07-19T04:40:20.796+0000" <name>Jack</name>
} <birthDate>2017-07-19T10:25:20.450+0000</birthDate>
] </item>
</List>
Questions
How do you implement Exception Handling for
RESTFul Web Services?
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
What are the different error status that you would
<artifactId>jackson-dataformat-xml</artifactId> return in RESTful Web Services?
</dependency>
How would you implement them using Spring Boot?
How do you handle Validation Errors with RESTful
Web Services?

Response Status GET http://localhost:8080/users/1000


200 - SUCCESS Get request to a non existing resource.
201 - CREATED {
"timestamp": "2017-07-19T05:28:37.534+0000"
404 - RESOURCE NOT FOUND "status": 500,
400 - BAD REQUEST "error": "Not Found",
"message": "id-500",
401 - UNAUTHORIZED "path": "/users/500"
500 - SERVER ERROR }
GET http://localhost:8080/users/1000
Get request to a non existing resource.
Default Spring Boot Structure.
@ResponseStatus(HttpStatus.NOT_FOUND) {
public class UserNotFoundException extends RuntimeException { "timestamp": "2017-07-19T05:28:37.534+0000"
"status": 404,
"error": "Not Found",
"message": "id-500",
"path": "/users/500"
}

GET http://localhost:8080/users/1000
Get request to a non existing resource.
The response shows a Customized Message public class ExceptionResponse {
private Date timestamp;
Structure private String message;
private String details;
{
"timestamp": "2017-07-19T05:31:01.961+0000",
"message": "id-500",
"details": "Any details you would want to add"
}
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions
(Exception ex, WebRequest request) {
@ControllerAdvice
ExceptionResponse exceptionResponse
@RestController
= new ExceptionResponse(new Date(), ex.getMessage(),
public class CustomizedResponseEntityExceptionHandler
request.getDescription(false));
extends ResponseEntityExceptionHandler {
return new ResponseEntity(exceptionResponse,
HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException POST http://localhost:8080/users with
UserNotFoundException ex, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(),
Validation Errors
request.getDescription(false)); {
"name": "R",
return new ResponseEntity(exceptionResponse, "birthDate": "2000-07-19T04:29:24.054+0000"
HttpStatus.NOT_FOUND); }
}
@Entity
public class User {
Response - 400 Bad Request @Id
@GeneratedValue
{
private Integer id;
"timestamp": "2017-07-19T09:00:27.912+0000",
"message": "Validation Failed",
@Size(min=2, message="Name should have atleast 2 characters")
"details": "org.springframework.validation.BeanPropertyBindingResult:
@ApiModelProperty(notes="Name should have atleast 2 characters"
1 errors\nField error in object 'user' on field 'name': rejected value [R]; codes [Size.user.name,Size.name,Size.java.lang.String,Size]; arguments [org.sprin
private String name;
default message [Name should have atleast 2 characters]"
}
@Past
@ApiModelProperty(notes="Birth date should be in the past")
private Date birthDate;

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
@PostMapping("/users")
HttpHeaders headers, HttpStatus status, WebRequest request)
public ResponseEntity<Object>
ExceptionResponse exceptionResponse = new ExceptionResponse(
createUser(@Valid @RequestBody User user) {
new Date(), "Validation Failed",ex.getBindingResult().toString());
return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
}
Questions public class PersonV1 {
private String name;

Why do we need Versioning for RESTful Web public class PersonV2 {


Services? private Name name;

What are the versioning options that are available? public class Name {
How do you implement Versioning for RESTful Web private String firstName;
private String lastName;
Services?

Versioning Options Versioning Options


URI Versioning
http://localhost:8080/v1/person Header Versioning
http://localhost:8080/v2/person http://localhost:8080/person/header
Request Param Versioning headers=[X-API-VERSION=1]
http://localhost:8080/person/param?version=1 http://localhost:8080/person/header
http://localhost:8080/person/param?version=2 headers=[X-API-VERSION=2]
Versioning Options
MIME Time or Accept Header Versioning @GetMapping("v1/person")
http://localhost:8080/person/produces public PersonV1 personV1() {
return new PersonV1("Bob Charlie");
produces=[application/vnd.company.app- }
v1+json] @GetMapping("v2/person")
http://localhost:8080/person/produces public PersonV2 personV2() {
return new PersonV2(new Name("Bob", "Charlie"));
produces=[application/vnd.company.app- }
v2+json]

@GetMapping(value = "/person/param", @GetMapping(value = "/person/header",


params = "version=1") headers = "X-API-VERSION=1")
public PersonV1 paramV1() { public PersonV1 headerV1() {
return new PersonV1("Bob Charlie"); return new PersonV1("Bob Charlie");
} }

@GetMapping(value = "/person/param", @GetMapping(value = "/person/header",


params = "version=2") headers = "X-API-VERSION=2")
public PersonV2 paramV2() { public PersonV2 headerV2() {
return new PersonV2(new Name("Bob", "Charlie")); return new PersonV2(new Name("Bob", "Charlie"));
} }
Versioning
Media type versioning (a.k.a “content negotiation”
@GetMapping(value = "/person/produces",
produces = "application/vnd.company.app-v1+json")
or “accept header”)
public PersonV1 producesV1() { GitHub
}
return new PersonV1("Bob Charlie");
(Custom) headers versioning
Microso
@GetMapping(value = "/person/produces",
produces = "application/vnd.company.app-v2+json") URI Versioning
public PersonV2 producesV2() { Twitter
return new PersonV2(new Name("Bob", "Charlie"));
} Request Parameter versioning
Amazon

Versioning
Factors Questions
URI Pollution Which is the client you use to test RESTful Web
Misuse of HTTP Headers Services?
Caching How do you use Postman to execute RESTful Service
Can we execute the request on the browser? Requests?
API Documentation How can you send Request Headers using Postman?
No Perfect Solution
Postman
Thank You

You might also like