Spring Interview Questions
Spring Interview Questions
Spring Interview Questions
Spring
Covers 200+ Interview Questions about
Spring
Spring MVC
@Autowired @Autowired
TodoDataService dataService;// = new TodoDataService() private SortAlgorithm sortAlgorithm;
Dependency Injection
We use Spring Framework to instantiate beans and
Inversion of Control
wire dependencies public class ComplexAlgorithmImpl {
@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 {
@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?
@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?
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"});
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 {
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>
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";
}
@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
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();
}
}
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?
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
st.execute();
st.close();
connection.close();
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;
@OneToOne
private Passport passport;
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 }
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;
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";
}
}
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
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>
Endpoint
@PayloadRoot(namespace = "http://in28minutes.com/courses",
localPart = "GetCourseDetailsRequest")
@ResponsePayload
public GetCourseDetailsResponse processCourseDetailsRequest Questions
(@RequestPayload GetCourseDetailsRequest request) {
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
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
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(
}
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?
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?
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;
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
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