Spring Interview Questions PDF
Spring Interview Questions PDF
Interview Questions
A 5 Hour Video Course
Covers 200+ Interview Questions about
Spring
Spring MVC
Spring Boot
JPA, Sprint Data, Spring Data JPA
Spring Web Services
Spring REST
Find more about this at
http://www.in28minutes.com
Questions
What is loose coupling?
What is a Dependency?
What is IOC (Inversion of Control)?
What is Dependency Injection?
Can you give few examples of Dependency
Injection?
What is Auto Wiring?
Tight Coupling
public class TodoBusinessService {
BubbleSortAlgorithm bubbleSortAlgorithm
= new BubbleSortAlgorithm();
Loose Coupling
@Component
public class TodoBusinessService {
@Autowired
TodoDataService dataService;// = new TodoDataService()
@Autowired
private SortAlgorithm sortAlgorithm;
@Component
public class ComplexAlgorithmImpl {
@Autowired
private SortAlgorithm sortAlgorithm;
Inversion of Control
public class ComplexAlgorithmImpl {
BubbleSortAlgorithm bubbleSortAlgorithm
= new BubbleSortAlgorithm();
@Component
public class ComplexAlgorithmImpl {
@Autowired
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
Find Beans
Wire Dependencies
Manage Lifecycle of the Bean
IOC Container
@Component
public class ComplexAlgorithmImpl {
@Autowired
private SortAlgorithm sortAlgorithm;
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
ApplicationContext context =
new ClassPathXmlApplicationContext(
new String[] {"BusinessApplicationContext.xml",
"Other-Configuration.xml"});
@Configuration
class SpringContext {
}
ApplicationContext ctx =
new AnnotationConfigApplicationContext(
SpringContext.class);
Unit Tests
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JavaTestContext.class)
public class DependencyInjectionJavaContextExamples {
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/TestContext.xml" })
public class TodoBusinessTest {
Questions
How does Spring know where to search for
Components or Beans?
What is a component scan?
How do you define a component scan in XML and
Java Configurations?
How is it done with Spring Boot?
Java Configuration
@Configuration
@ComponentScan(basePackages = {
"com.in28minutes.spring.example1.businessservice",
"com.in28minutes.spring.example1.dataservice.stub" })
class SpringContext {
}
XML Configuration
<?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"
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 h
http://www.springframework.org/schema/tx h
http://www.springframework.org/schema/cont
http://www.springframework.org/schema/aop
<context:component-scan
base-package="com.in28minutes.example"/>
</beans>
Spring Boot
package com.in28minutes.spring.basics.springin5steps;
@SpringBootApplication
public class SpringIn5StepsApplication {
package com.in28minutes.spring.basics.springin5steps;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringIn5StepsApplicationTests {
Questions
What does @Component signify?
What does @Autowired signify?
What’s the difference Between @Controller,
@Component, @Repository, and @Service
Annotations in Spring?
Notes
@Component - Spring should manage the bean.
@Autowired - Spring should find the matching bean
and wire the dependency in.
@Component
public class ComplexAlgorithmImpl {
@Autowired
private SortAlgorithm sortAlgorithm;
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
Notes
@Component - Generic Component
@Repository - encapsulating storage, retrieval, and
search behavior typically from a relational database
@Service - Business Service Facade
@Controller - Controller in MVC pattern
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
The singleton scope is the default scope in Spring.
The Gang of Four defines Singleton as having one
and only one instance per ClassLoader.
However, Spring singleton is defined as one instance
of bean definition per container.
Other Scopes
singleton - One instance per Spring Context
prototype - New bean whenever requested
request - One bean per HTTP request. Web-aware
Spring ApplicationContext.
session - One bean per HTTP session. Web-aware
Spring ApplicationContext.
Examples
@RequestScope
@Component
public class RequestScopedBean {
@SessionScope
@Component
public class SessionScopedBean {
TodoDataService dataService;
@Autowired
public void setDataService
(TodoDataService dataService) {
this.dataService = dataService;
}
//Through Reflection
@Component
public class TodoBusinessService {
@Autowired
TodoDataService dataService;
Constructor Injection
@Component
public class TodoBusinessService {
TodoDataService dataService;
@Autowired
public TodoBusinessService(TodoDataService dataService) {
super();
this.dataService = dataService;
}
Constructor vs Setter Injection
https://docs.spring.io/spring/docs/current/spring-
framework-reference/htmlsingle/
The Spring team generally advocates constructor
injection as it enables one to implement application
components as immutable objects and to ensure
that required dependencies are not null.
Constructor vs Setter Injection
Furthermore constructor-injected components are
always returned to client (calling) code in a fully
initialized state.
As a side note, a large number of constructor
arguments is a bad code smell.
Constructor vs Setter Injection
Constructor Injection for Mandatory Dependencies
Setter Injection for Optional Dependencies
Questions
What are the different options available to create
Application Contexts for Spring?
What is the difference between XML and Java
Configurations for Spring?
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"
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 h
http://www.springframework.org/schema/tx h
http://www.springframework.org/schema/cont
http://www.springframework.org/schema/aop
</beans>
ApplicationContext context =
new ClassPathXmlApplicationContext(
new String[] {"BusinessApplicationContext.xml",
"Other-Configuration.xml"});
Java
@Configuration
class SpringContext {
}
ApplicationContext ctx =
new AnnotationConfigApplicationContext(
SpringContext.class);
XML vs Java Configuration
Today, with use of annotations, the things that are
specified in a Application Context are at bare
minimum.
There is little to choose between these as long as
the configuration is at a bare minimum.
XML vs Java Configuration
With Spring Boot, we are slowly moving towards
complete Java Configuration.
package com.in28minutes.spring.basics.springin5steps;
@SpringBootApplication
public class SpringIn5StepsApplication {
Questions
How does Spring do Autowiring?
What are the different kinds of matching used by
Spring for Autowiring?
Autowiring
byType
byName
constructor - similar to byType, but through
constuctor
by Type - Class or Interface
@Component
public class ComplexAlgorithmImpl {
@Autowired
private SortAlgorithm sortAlgorithm;
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
by Name
@Component
public class ComplexAlgorithmImpl {
@Autowired
private SortAlgorithm quickSortAlgorithm;
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
@Component
public class BubbleSortAlgorithm implements SortAlgorithm {
Questions
How do you debug problems with Spring
Framework?
NoUniqueBeanDefinitionException
NoSuchBeanDefinitionException
What is @Primary?
What is @Qualifier?
No matching Components
@Component
public class ComplexAlgorithmImpl {
@Autowired
private SortAlgorithm sortAlgorithm;
@Autowired
private SortAlgorithm sortAlgorithm;
@Component
public class QuickSortAlgorithm implements SortAlgorithm {
@Component
public class BubbleSortAlgorithm implements SortAlgorithm {
Field sortAlgorithm in
springin5steps.BinarySearchImpl required a single
bean, but 2 were found:
bubbleSortAlgorithm: defined in file
[BubbleSortAlgorithm.class]
quickSortAlgorithm: defined in file
[QuickSortAlgorithm.class]
Primary
@Component
@Primary
public class BubbleSortAlgorithm implements SortAlgorithm {
Qualifier
@Component
public class ComplexAlgorithmImpl {
@Autowired
@Qualifier("mainAlgorithm")
private SortAlgorithm sortAlgorithm;
@Component
@Qualifier("mainAlgorithm")
public class BubbleSortAlgorithm implements SortAlgorithm {
Questions
What is CDI (Contexts and Dependency Injection)?
Does Spring Support CDI?
Would you recommed to use CDI or Spring
Annotations?
CDI
Java EE Dependency Injection Standard (JSR-330)
Spring Supports most annotations
@Inject (@Autowired)
@Named (@Component & @Qualifier)
@Singleton (Defines a scope of Singleton)
Questions
What are the major features in different versions of
Spring?
What are new features in Spring Framework 4.0?
What are new features in Spring Framework 5.0?
Notes
Spring 2.5 made annotation-driven configuration
possible.
Spring 3.0 made great use of the Java 5
improvements in language.
Spring 4.0
First version to fully support Java 8 features.
Minimum version of Java to use Spring 4 is Java SE
6.
Introduced @RestController annotation
Spring 4.1 supports JCache (JSR-107) annotations
Spring 5.0
Functional web framework
Support for Jigsaw (Java Modularity)
Support for reactive programming
Support for Kotlin
Questions
What are important Spring Modules?
Spring Modules
Questions
What are important Spring Projects?
Spring Projects
Spring Boot
Spring Cloud
Spring Data
Spring Integration
Spring Batch
Spring Security
Spring HATEOAS
Spring Web Services
Spring Session
Questions
What is the simplest way of ensuring that we are
using single version of all Spring related
dependencies?
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>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependencies>
Questions
Name some of the design patterns used in Spring
Framework?
Design Patterns in Spring
Front Controller - Dispatcher Servlet
Prototype - Beans
Dependency Injection
Factory Pattern - Bean Factory & Application Context
Template Method
org.springframework.web.servlet.mvc.AbstractCont
Questions
What are some of the important Spring annotations
you have used?
Annotations
@Component, @Service, @Repository, @Controller
@Autowired
@Primary
@Qualifier
@Configuration
Questions
What do you think about Spring Framework?
Why is Spring Popular?
Can you give a big picture of the Spring Framework?
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
Spring Projects
MVC
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
Spring MVC?
Can you explain a simple flow in Spring MVC?
What is a ViewResolver?
What is Model?
What is ModelAndView?
What is a RequestMapping?
Controller Method
@RequestMapping(value = "/list-todos",
method = RequestMethod.GET)
public String listTodos(ModelMap model) {
model.addAttribute("todos",
service.retrieveTodos(retrieveLoggedinUserName()));
return "list-todos";
}
ViewResolver
<bean
class=
"org.springframework.web.servlet.view.InternalResourceViewResolve
<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";
}
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Questions
What is a form backing object?
How is validation done using Spring MVC?
What is BindingResult?
How do you map validation results to your view?
What are Spring Form Tags?
Show New Todo Page
@RequestMapping(value = "/add-todo",
method = RequestMethod.GET)
public String showTodoPage(ModelMap model) {
}
todo.jsp
<form:form method="post" commandName="todo">
<fieldset>
<form:label path="desc">Description</form:label>
<form:input path="desc" type="text"/>
<form:errors path="desc"/>
</fieldset>
<fieldset>
<form:label path="targetDate">Target Date</form:label>
<form:input path="targetDate" type="text" />
<form:errors path="targetDate"/>
</fieldset>
<input type="submit" value="Submit" />
</form:form>
Add Todo
@RequestMapping(value = "/add-todo", method = RequestMethod.POST)
public String addTodo(ModelMap model, @Valid Todo todo,
BindingResult result) {
if (result.hasErrors()) {
return "todo";
}
service.addTodo(retrieveLoggedinUserName(), todo.getDesc(), new
false);
model.clear();
return "redirect:list-todos";
}
Todo.java
public class Todo {
@ExceptionHandler(value = Exception.class)
public String handleException
(HttpServletRequest request, Exception ex) {
logger.error("Request " + request.getRequestURL()
+ " Threw an Exception", ex);
return "error";
}
}
Questions
Why is Spring MVC so popular?
Spring MVC
Clear Seperation of Concerns
Dispatcher Servlet
View Resolver
View
Model
We will discuss more "Spring
MVC" questions in the section on
RESTful Webservices.
Spring Boot
Questions
What is Spring Boot?
What are the important Goals of Spring Boot?
What are the important Features of Spring Boot?
Why Spring Boot?
Spring based applications have a lot of
configuration.
When we use Spring MVC, we need to configure
component scan, dispatcher servlet, a view resolver,
web jars(for delivering static content) among other
things.
Why Spring Boot?
World is moving towards Microservices.
We do not have a lot of time to set up 100
microservices.
Spring Boot Goals
Quick Start to Spring
Be opinionated
Non functional features
No code generation
Spring Boot Features
Auto Configuration
Spring Boot Starter Projects
Spring Boot Actuator
Embedded Server
Questions
Compare Spring Boot vs Spring?
Compare Spring Boot vs Spring MVC?
Spring
Most important feature of Spring
Framework is Dependency Injection. At
the core of all Spring Modules is
Dependency Injection or IOC Inversion
of Control.
@RestController
public class WelcomeController {
@RequestMapping("/welcome")
public String welcome() {
return service.retrieveWelcomeMessage();
}
}
With Spring
@Component
public class WelcomeService {
//Bla Bla Bla
}
@RestController
public class WelcomeController {
@Autowired
private WelcomeService service;
@RequestMapping("/welcome")
public String welcome() {
return service.retrieveWelcomeMessage();
}
}
Problems Spring Solves
Problem 1 : Duplication/Plumbing Code
Problem 2 : Good Integration with Other
Frameworks.
Spring MVC
Spring MVC Framework provides
decoupled way of developing web
applications. With simple concepts like
Dispatcher Servlet, ModelAndView and
View Resolver, it makes it easy to
develop web applications.
Spring Boot
Eliminates all configuration needed by Spring and
Spring MVC and auto configures it
No need for @ComponentScan. Default
Component Scan.
No need to configure DispatcherServlet
No need to configure a Data Source, Entity
Manager Factory or Transaction Manager.
Spring Boot Thinking
Can we bring more intelligence into
this? When a spring mvc jar is added
into an application, can we auto
configure some beans automatically?
Spring Boot Thinking
Spring Boot looks at
Frameworks available on the CLASSPATH
Existing configuration for the application.
<java.version>1.6</java.version>
<resource.delimiter>@</resource.delimiter> <!-- delimiter that does
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEn
<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>
<hibernate.version>5.0.9.Final</hibernate.version>
<hibernate-validator.version>5.2.4.Final</hibernate-validator.versi
<jackson.version>2.8.1</jackson.version>
....
<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>
Questions
What is Spring Initializr?
Spring Initializr http://start.spring.io/ is
great tool to bootstrap your Spring
Boot projects.
Questions
What is application.properties?
What are some of the important things that can
customized in application.properties?
application.properties is used to
configure your Spring Boot Application
Example Configuration
logging.file=
logging.level.*=
spring.autoconfigure.exclude=
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
Boot?
How can you add custom application properties
using Spring Boot?
What is @ConfigurationProperties?
logging:
level:
org.springframework: DEBUG
app:
name: In28Minutes
description: ${app.name} is your first Spring Boot application
import
org.springframework.boot.context.properties.ConfigurationPropertie
@Component
@ConfigurationProperties("basic")
public class BasicConfiguration {
private boolean value;
private String message;
private int number;
@Autowired
private BasicConfiguration configuration;
@RequestMapping("/dynamic-configuration")
public Map dynamicConfiguration() {
// Not the best practice to use a map to store differnt types!
Map map = new HashMap();
map.put("message", configuration.getMessage());
map.put("number", configuration.getNumber());
map.put("key", configuration.isValue());
return map;
}
application.properties
basic.value= true
basic.message= Dynamic Message
basic.number= 100
application.yaml
basic:
value: true
message: Dynamic Message YAML
number: 100
Advantage
Type Safety
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target
com.in28minutes.springboot.configuration.BasicConfiguration@391b854
failed:
Property: basic.number
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
Good Practice
Design all your application configuration using
ConfigurationProperties
Questions
What is a profile?
How do you define beans for a specific profile?
How do you create application configuration for a
specific profile?
Profile
How do you have different
configuration for different
environments?
Profile
application-dev.properties
application-qa.properties
application-stage.properties
application-prod.properties
application.properties
Profile
Based on the active profile, appropriate
configuration is picked up.
Used to Configure Resources - Databases, Queues,
External Services
Setting a profile
Using -Dspring.profiles.active=prod in VM
Arguments
In application.properties,
spring.profiles.active=prod
Profiles in code
@Profile("dev") on a bean
@Profile("dev")
@Bean
public String devBean() {
return "I will be available in profile dev";
}
@Profile("prod")
@Bean
public String prodBean() {
return "I will be available in profile prod";
}
Questions
What is Spring Boot Actuator?
How do you monitor web services using Spring Boot
Actuator?
How do you find more information about your
application envrionment using Spring Boot?
Spring Boot Actuator
Monitoring
/env, /metrics, /trace, /dump
/beans, / autoconfig, /configprops, /mappings
URL has changed in Spring Boot 2.0 - /application
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Questions
What is a CommandLineRunner?
CommandLineRunner
Spring Documentation - interface used
to indicate that a bean should run
when it is contained within a
SpringApplication
PreparedStatement st = connection.prepareStatement(
"Update todo set user=?, desc=?, target_date=?, is_done=? where i
st.setString(1, todo.getUser());
st.setString(2, todo.getDesc());
st.setTimestamp(3, new Timestamp(todo.getTargetDate().getTime()));
st.setBoolean(4, todo.isDone());
st.setInt(5, todo.getId());
st.execute();
st.close();
connection.close();
Spring JDBC
jdbcTemplate
.update
("Update todo set user=?, desc=?, target_date=?, is_done=? where i
todo.getUser(), todo.getDesc(),
new Timestamp(todo.getTargetDate().getTime()),
todo.isDone(), todo.getId());
todo.setId(rs.getInt("id"));
todo.setUser(rs.getString("user"));
todo.setDesc(rs.getString("desc"));
todo.setTargetDate(
rs.getTimestamp("target_date"));
todo.setDone(rs.getBoolean("is_done"));
return todo;
}
}
Spring JDBC - RowMapper
return jdbcTemplate.query(
"SELECT * FROM TODO where user = ?",
new Object[] { user }, new TodoMapper());
return jdbcTemplate.queryForObject(
"SELECT * FROM TODO where id=?",
new Object[] { id }, new TodoMapper())
Questions
What is JPA?
What is Hibernate?
How do you define an entity in JPA?
What is an Entity Manager?
What is a Persistence Context?
JPA - Update Todo
Defining an entity
@Entity
@Table(name = "Todo")
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@PersistenceContext
private EntityManager entityManager;
@Override
public void updateTodo(Todo todo) {
entityManager.merge(todo);
}
Questions
How do you map relationships in JPA?
What are the different types of relationships in JPA?
How do you define One to One Mapping in JPA?
How do you define One to Many Mapping in JPA?
How do you define Many to Many Mapping in JPA?
One to One Relationship
@Entity
public class Passport {
....
// Inverse Relationship
// bi-directional OneToOne relationship
// Column will not be created in the table
// Try removing mappedBy = "passport" => You will see that studen
// will be created in passport
@OneToOne(fetch = FetchType.LAZY, mappedBy = "passport")
private Student student;
@Entity
@Table(name = "Student")
public class Student {
@OneToOne
private Passport passport;
One to Many Relationship
@Entity
public class Project {
@OneToMany(mappedBy = "project")
private List<Task> tasks;
@Entity
public class Task {
@ManyToOne
@JoinColumn(name="PROJECT_ID")
private Project project;
Many to Many Relationship
@Entity
public class Project {
@ManyToMany
// @JoinTable(name="STUDENT_PROJ",
// joinColumns=@JoinColumn(name="STUDENT_ID"),
// inverseJoinColumns=@JoinColumn(name="PROJECT_ID"))
private List<Student> students;
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="2.0">
<persistence-unit name="hsql_pu" transaction-type="RESOURCE_LOCAL
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provi
<properties>
<property name="hibernate.dialect" value="org.hibernate.diale
<property name="hibernate.connection.url" value="jdbc:hsqldb:
<property name="hibernate.connection.driver_class" value="org
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
</properties>
</persistence-unit>
</persistence>
Configure Entity Manager
Factory and Transaction
Manager
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerF
id="entityManagerFactory">
<property name="persistenceUnitName" value="hsql_pu" />
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"
Making Service Transactional
@Service
public class StudentService {
@Autowired
StudentRepository service;
@Transactional
public Student insertStudent(Student student) {
return service.insertStudent(student);
}
@Service
@Transactional
public class StudentService {
@Autowired
StudentRepository service;
Spring Data
Questions
What is Spring Data?
What is the need for Spring Data?
What is Spring Data JPA?
Duplication in JPA Repositories
Passport Repository
@PersistenceContext
private EntityManager entityManager;
//Page Size - 10
PageRequest pageable = new PageRequest(0,10);
Page<Passport> page = passportRepository.findAll(pageable);
System.out.println(userPage.getTotalPages());
System.out.println(userPage.nextPageable());
Unit Testing
Questions
How does Spring Framework Make 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 {
private DataService dataService;
//Constructor - public SomeBusinessImpl(DataService dataService)
int findTheGreatestFromAllData() {
int[] data = dataService.retrieveAllData();
int greatest = Integer.MIN_VALUE;
SomeBusinessImpl businessImpl =
new SomeBusinessImpl(dataServiceMock);
assertEquals(24, result);
}
Using Annotations
@RunWith(MockitoJUnitRunner.class)
public class SomeBusinessMockAnnotationsTest {
@Mock
DataService dataServiceMock;
@InjectMocks
SomeBusinessImpl businessImpl;
@Test
public void testFindTheGreatestFromAllData() {
when(dataServiceMock.retrieveAllData())
.thenReturn(new int[] { 24, 15, 3 });
assertEquals(24, businessImpl.findTheGreatestFromAllData());
}
Questions
What is MockMvc?
What is @WebMvcTest?
What is @MockBean?
How do you write a unit test with MockMVC?
What is JSONAssert?
Mock MVC Test with Spring Boot
public Question retrieveDetailsForQuestion(
@PathVariable String surveyId,
@PathVariable String questionId) {
return
surveyService.retrieveQuestion(surveyId, questionId);
}
Mock MVC Test with Spring Boot
@RunWith(SpringRunner.class)
@WebMvcTest(value = SurveyController.class, secure = false)
public class SurveyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private SurveyService surveyService;
Mock MVC Test - Continued
@Test
public void retrieveDetailsForQuestion() throws Exception {
Question mockQuestion = new Question("Question1",
"Largest Country in the World", "Russia", Arrays.asList(
"India", "Russia", "United States", "China"));
Mockito.when(
surveyService.retrieveQuestion(Mockito.anyString(), Mockito
.anyString())).thenReturn(mockQuestion);
String expected =
"{id:Question1,description:Largest Country in the World,correct
JSONAssert.assertEquals(expected, result.getResponse()
.getContentAsString(), false);
// Assert
}
Questions
How do you write an integration test with Spring
Boot?
What is @SpringBootTest?
What is @LocalServerPort?
What is TestRestTemplate?
Integration Test with Spring Boot
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SurveyControllerIT {
@LocalServerPort
private int port;
}
Integration Test with Spring Boot
@Test
public void testRetrieveSurveyQuestion() {
if (course == null)
throw new CourseNotFoundException("Invalid Course Id " + reques
return mapCourseDetails(course);
}
Questions
What is a MessageDispatcherServlet?
How do you configure a MessageDispatcherServlet?
MessageDispatcherServlet
@Bean
public ServletRegistrationBean messageDispatcherServlet
(ApplicationContext context) {
MessageDispatcherServlet messageDispatcherServlet
= new MessageDispatcherServlet();
messageDispatcherServlet.setApplicationContext(context);
messageDispatcherServlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(messageDispatcherServlet,
"/ws/*");
}
Questions
How do you generate a WSDL using Spring Web
Services?
@Bean(name = "courses")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema co
DefaultWsdl11Definition definition = new DefaultWsdl11Definition(
definition.setPortTypeName("CoursePort");
definition.setTargetNamespace("http://in28minutes.com/courses"
definition.setLocationUri("/ws");
definition.setSchema(coursesSchema);
return definition;
}
@Bean
public XsdSchema coursesSchema() {
return new SimpleXsdSchema(
new ClassPathResource("course-details.xsd"));
}
Questions
How do you implement error handling for SOAP Web
Services?
What is a SOAP Fault?
Endpoint
@PayloadRoot(namespace = "http://in28minutes.com/courses",
localPart = "GetCourseDetailsRequest")
@ResponsePayload
public GetCourseDetailsResponse processCourseDetailsRequest
(@RequestPayload GetCourseDetailsRequest request) {
if (course == null)
throw new CourseNotFoundException("Invalid Course Id " + reques
return mapCourseDetails(course);
}
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring xml:lang="en">Invalid Course Id 1000</faul
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
@SoapFault(
faultCode = FaultCode.CUSTOM,
customFaultCode =
"{http://in28minutes.com/courses}001_COURSE_NOT_FOUND"
)
public class CourseNotFoundException extends RuntimeException {
}
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/
<SOAP-ENV:Header />
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode xmlns:ns0="http://in28minutes.com/courses">
ns0:001_COURSE_NOT_FOUND</faultcode>
<faultstring xml:lang="en">
Invalid Course Id 1234</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
RESTful Web
Services
Questions
What is REST?
REpresentational State Transfer
REST is a style of so ware architecture
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
Example
Create a User - POST /users
Delete a User - DELETE /users/1
Get all Users - GET /users
Get one Users - GET /users/1
REST
Data Exchange Format
No Restriction. JSON is popular
Transport
Only HTTP
Service Definition
No Standard. WADL/Swagger/...
Questions
What are the Best Practices of RESTful Services?
Best Practices in
RESTful Design
Consumer First
Make best use of
HTTP
Request Methods
GET
POST
PUT
DELETE
Response Status
200 - SUCCESS
404 - RESOURCE NOT FOUND
400 - BAD REQUEST
201 - CREATED
401 - UNAUTHORIZED
500 - SERVER ERROR
No Secure Info in URI
Use Plurals
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?
What happens when we return a bean from a
Request Mapping Method?
What is GetMapping and what are the related
methods available in Spring MVC?
@GetMapping("/users")
public List<User> retrieveAllUsers() {
return service.findAll();
}
Questions
Can you show the code for an example Post
Resource method with Spring REST?
Why do we use ResponseEntity in a RESTful Service?
@PostMapping("/users")
public ResponseEntity<Object> createUser(
@Valid @RequestBody User user) {
User savedUser = service.save(user);
return ResponseEntity.created(location).build();
}
Questions
What is HATEOAS?
Can you give an Example Response for HATEOAS?
How do we implement it using Spring?
HATEOAS
Hypermedia as The Engine of Application State
Example
When requested for details of a facebook post, we
return
Link for actions to like, unlike or comment on
the post
{
"id": 1,
"name": "Adam",
"birthDate": "2017-07-19T09:26:18.337+0000",
"_links": {
"all-users": {
"href": "http://localhost:8080/users"
}
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
@GetMapping("/users/{id}")
public Resource<User> retrieveUser
(@PathVariable int id) {
User user = service.findOne(id);
ControllerLinkBuilder linkTo =
linkTo(methodOn(this.getClass()).retrieveAllUsers());
resource.add(linkTo.withRel("all-users"));
return resource;
}
Questions
How do you document RESTful web services?
Can you give a brief idea about Swagger
Documentation?
How do you automate generation of Swagger
Documentation from RESTful Web Services?
How do you add custom information to Swagger
Documentation generated from RESTful Web
Services?
What is Swagger-UI?
OpenAPI Specification (formerly called the Swagger
Specification).
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2);
}
}
public static final Contact DEFAULT_CONTACT = new Contact(
"Ranga Karanam", "http://www.in28minutes.com", "in28minutes@gma
@Id
@GeneratedValue
private Integer id;
@Past
@ApiModelProperty(notes="Birth date should be in the past")
private Date birthDate;
@PostMapping("/users")
public ResponseEntity<Object>
createUser(@Valid @RequestBody User user) {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request)
ExceptionResponse exceptionResponse = new ExceptionResponse(
new Date(), "Validation Failed",ex.getBindingResult().toStr
return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUE
}
Questions
Why do we need Versioning for RESTful Web
Services?
What are the versioning options that are available?
How do you implement Versioning for RESTful Web
Services?
public class PersonV1 {
private String name;
@GetMapping("v2/person")
public PersonV2 personV2() {
return new PersonV2(new Name("Bob", "Charlie"));
}
@GetMapping(value = "/person/param",
params = "version=1")
public PersonV1 paramV1() {
return new PersonV1("Bob Charlie");
}
@GetMapping(value = "/person/param",
params = "version=2")
public PersonV2 paramV2() {
return new PersonV2(new Name("Bob", "Charlie"));
}
@GetMapping(value = "/person/header",
headers = "X-API-VERSION=1")
public PersonV1 headerV1() {
return new PersonV1("Bob Charlie");
}
@GetMapping(value = "/person/header",
headers = "X-API-VERSION=2")
public PersonV2 headerV2() {
return new PersonV2(new Name("Bob", "Charlie"));
}
@GetMapping(value = "/person/produces",
produces = "application/vnd.company.app-v1+json")
public PersonV1 producesV1() {
return new PersonV1("Bob Charlie");
}
@GetMapping(value = "/person/produces",
produces = "application/vnd.company.app-v2+json")
public PersonV2 producesV2() {
return new PersonV2(new Name("Bob", "Charlie"));
}
Versioning
Media type versioning (a.k.a “content negotiation”
or “accept header”)
GitHub
(Custom) headers versioning
Microso
URI Versioning
Twitter
Request Parameter versioning
Amazon
Versioning
Factors
URI Pollution
Misuse of HTTP Headers
Caching
Can we execute the request on the browser?
API Documentation
No Perfect Solution
Questions
Which is the client you use to test RESTful Web
Services?
How do you use Postman to execute RESTful Service
Requests?
How can you send Request Headers using Postman?
Postman
Thank You