Spring Interview Questions [2020]


Spring Framework


What is the principle on which Spring framework is based on?


Spring framework is based on 'Inversion Of Control (IoC)' principle, also know as 'Dependency Injection (DI)' principle.

In this principle objects define their dependencies in configuration metadata. The IOC container looks up the configuration metadata and injects the dependencies when it creates object instance.

Since this process is inverse of objects creating instances of their dependencies, this principle is known as the 'Inversion Of Control (IOC) principle'. Since dependent object instances are injected into the object instance, this principle is also know a 'Dependency Injection (DI) principle.'


How does Spring framework implement the 'Inversion Of Control (IoC)' principle?


Spring framework implements an 'Inversion Of Control (IoC)' container, known as Spring IoC container, which manages the life-cycle of objects, known as Beans, in an application. The Spring IoC container is responsible for instantiating, configuring and assembling the beans in an application.'

Beans, and the dependencies among them, are maintained via configuration metadata by the application developer. The configuration metadata can be represented in XML or Java annotations. The Spring IoC container looks up the configuration metadata, instantiates dependent beans, and injects them into the bean that it is instantiating.


How is the Spring IoC container implemented?


Spring framework provides the 'org.springframework.context' and 'org.springframework.beans' packages that represents the Spring IoC container.

BeanFactory - 'org.springframework.context.BeanFactory' provides the configuration framework and functionality.

ApplicationContext - 'org.springframework.context.ApplicationContext' interface which extends from BeanFactory interface provides more enterprise specific functionality.

WebApplicationContext - In addition Spring framework also provides application-layer specific contexts such as WebApplicationContext that can be used in web applications.

ApplicationContext Implementations - Spring framework provides several implementations of the ApplicationContext interface. For XML based configuration metadata, the commonly used implementations are ClassPathXmlApplicationContext and FileSystemXmlApplicationContext.


What are the different formats in which you can maintain configuration metadata in Spring framework?


In Spring framework you can maintain configuration metadata in following formats.

XML-based configuration - Configuration metadata is traditionally maintained in XML format.

Annotation-based configuration - From Spring version 2.5, you can maintain configuration metadata using annotations.

Java-based configuration - From Spring version 3.0 onwards, you can use Java annotations, provided by Spring JavaConfig project. This is the most commonly used format now.


What are some of the key properties that are defined in the configuration metadata of a bean?


Following are some of the properties that are defined in the configuration metadata of a bean.

id - Specifies a unique identifier for the bean.

Class - Specifies the type of the class that has to be instantiated.

Name - Specifies one or more aliases for the bean that it can be referred to by.

Scope - Specifies the scope of the bean instance - singleton, prototype, request, session, application, or websocket.

Constructor args - Specifies the arguments that the Spring IOC container uses for constructor-based dependency injection.

Properties - Specifies the arguments that the Spring IoC container uses for setter-based dependency injection.

Autowiring mode - Specifies the autowire mode - no, byName, byType, or constructor.

lazy-init - Specifies if the bean instance has to be created when it is first requested, rather than at startup.



How do you specify the configuration for a bean in Spring framework?


In XML-based configuration you use the elements <beans/> and <bean/> to configure beans whose lifecycle will be handled by Spring IoC container.

In Java-based configuration the annotations @configuration and @bean are used to configure beans whose lifecycle will be handled by Spring IoC container.

@configuration is a class level annotation and plays the same role as <beans/&t; element. It indicates that the primary purpose of the class is that it is a source of bean configurations.

@Bean is a method level annotation which indicates that the method instantiates and returns a bean that will be managed by the Spring IoC container.

//XML-based bean configuration
<beans>
 <bean id='bean1' class='com.interviewgrid.Bean1'>...</bean>
 <bean id='bean2' class='com.interviewgrid.Bean2'>...</bean>
</beans>
//Java-based bean configuration
@Configuration
public class MyConfiguration {
 @Bean
 public MyBean1 myBean1() {
  return new MyBean1();
 }
 @Bean
 public MyBean2 myBean2() {
  return new MyBean2();
 }
}

What are are the different ways of instantiating beans?


Following are the three different ways of instantiating beans.

Instantiation with a constructor - Spring framework can instantiate and manage any Java class. With XML-based configuration you can specify the bean class as follows.

<bean id='myBean' class='com.interviewgrid.MyBean'/>

Instantiation with a static factory Method - Spring framework can instantiate and manage any class defined to be instantiated with a static factory method. With XML-based configuration you can specify the bean class as follows.

<bean id='myBean' class='com.interviewgrid.MyBean' factory-method='getInstance'/>

Instantiation with an instance factory - Spring framework can instantiate and manage any class defined to be instantiated with an instance factory method. With XML-based configuration you can specify the bean class as follows.

<bean id='myBean' factory-bean='com.interviewgrid.MyBean' factory-method='getInstance'/>

//Instantiation with a constructor
<bean id='myBean' class='com.interviewgrid.MyBean'/>
//Instantiation with a static factory method
<bean id='myBean' class='com.interviewgrid.MyBean' factory-method='getInstance'/>
//Instantiation with an instance factory method
<bean id='myBean' class='com.interviewgrid.MyBean' factory-method='getInstance'/>

What are are the two variants of dependency injection that Spring Framework supports?


Spring framework supports two variants of dependency injection. Constructor-based dependency injection and Setter-based dependency injection.

Constructor-based Dependency Injection - In constructor based dependency injection, the Spring IOC container invokes the constructor of the class that it is instantiating, and injects the arguments to the constructor.

With XML-based configuration you can specify the constructor args using the <constructor-arg> element.

Setter-based Dependency Injection - In setter based dependency, the Spring IOC container instantiates the class using constructor, and then calls the setter methods of the class to inject the dependencies.

With XML-based configuration you can specify the constructor args using the <property> element.

//Constructor-based dependency injection
<beans>
 <bean id='myBean1' class='com.interviewgrid.MyBean1'>
  <constructor-arg ref='myBean2'/>
 </bean>
 <bean id='myBean2' class='com.interviewgrid.MyBean2'/>
</beans>
//Setter based dependency injection
<beans>
 <bean id='myBean1' class='com.interviewgrid.MyBean1'>
  <property name='myBean2' ref='myBean2'/>
 </bean>
 <bean id='myBean2' class='com.interviewgrid.MyBean2'/>
</beans>

How do you dependency inject Java collection types using XML_based configuration?


You can use the elements ,,, and to dependency inject Java collection types.

<bean id='myBean' class='com.interviewgrid.MyBean'>
 //properties - results in a setMyEmails(java.util.Properties) call
 <property name='myEmails'>
  <props>
   <prop key='administrator'>[email protected]</prop>
   <propkey='support'>[email protected]</prop>
   <prop key='development'>[email protected]</prop>
  </props>
 </property>
 //list - results in a setMyList(java.util.List) call
 <property name='myList'>
  <list>
   <value>value1</value>
   <value>value2</value>
  </list>
 </property>
 //map - results in a setMyMap(java.util.Map) call
 <property name='myMap'>
  <map>
   <entry key='key1' value='value1'/>
   <entry key='key2' value='value2'/>
  </map>
 </property>
 //set - results in a setMySet(java.util.set) call
 <property name='someSet'>
  <set>
   <value>value1</value>
   <value>value2</value>
  </set>
 </property>
</bean>

What do you mean by lazy initialization of beans? How do you configure a bean to be lazy initialized?


By default the Sprint IOC container, or the ApplicationContext, eagerly instantiates all singleton beans as part of the initialization process.

You can configure a singleton bean such that the Spring IOC container does not instantiate this bean as part of the initialization process. This is known as lazy-initialization of the bean.

In XML-based configuration this property is controlled by using the lazy-init attribute on the <bean/> element.

<bean id='myLazyBean' class='com.interviewgrid.MyLazyBean' lazy-init='true'/>


What are are the different bean scopes supported by Spring framework?


Spring framework supports six bean scopes. Four of the six scopes are available only for web-aware application context.

Singleton - Singleton scope is the default scope for beans. In singleton scope a single bean instance is created for a single bean definition for each Spring IoC container.

Prototype - In prototype scope multiple bean instances are created for a single bean definition. Every request to a prototype bean results in the creation of a new bean instance.

Request - In Request scope a different bean instance is created for each HTTP request.

Session - In Session scope a different bean instance is created for each HTTP session.

Application - In Application scope a different bean instance is created for each HTTP ServletContext.

WebSocket - In WebSocket scope a different bean instance is created for each WebSocket.

In XML-based configuration the scope of a bean is specified by the scope attribute on the <bean/> element.

In Java-based configuration the scope of a bean is specified by the @scope annotation defined on the method that instantiates and returns the bean.

//XML_based bean configuration
//Prototype scoped bean
<bean id='MyPrototypeBean' class='com.interviewgrid.MyPrototypeBean' scope='prototype'/>
//Java-based bean configuration
@Configuration
public class MyConfiguration {
 @Bean
 @scope('prototype')
 public MyPrototypeBean myProtoTypeBean() {
  return new MyPrototypeBean();
 }
}

Can you dependency-inject a prototype scoped bean to a Singleton scoped bean.


You can dependency-inject a prototype scoped bean to a singleton scoped bean. However, a single instance of the prototype scoped bean is created and injected into the singleton scoped bean at initialization time. So at runtime a singleton scoped bean has a reference to the same instance of prototype scoped bean.

If you require a different instance of the prototype scoped bean for each method invocation on the singleton bean then you can use method injection.


How do you dependency inject a shorter-lived scoped bean into a longer-lived scoped bean?


You can dependency inject a shorter-lived scoped bean (example - session scoped bean) into a longer-lived scoped bean (example - singleton) by using a proxy for the shorter-lived scoped bean.

As part of the initialization process, the IoC container creates a proxy object for the shorter-lived scoped bean and injects it into the singleton bean.

When a method is invoked on the proxy object, the proxy fetches the real object (in this example from session) and invokes the method on that object.

In XML_based configuration the proxy is configured using the element '<aop:scoped-proxy/>'

In java-based configuration the @scope annotation provides similar support.


//XML_based configuration - session scoped bean
<bean id='MySessionBean' class='com.interviewgrid.MySessionBean' scope='session'
 <aop:scoped-proxy/>
</bean>
//java-based configuration - session scoped bean
@Bean
@SessionScope
public MySessionBean mySessionBean() {
 return new MySessionBean();
}

How do you load the configurations from one configuration class into another configuration class using Java-based configuration?


You can load the configuration definitions from one configuration class into another configuration class using the @import annotation.

@Configuration
public Class MyConfigA { ... }
@Configuration
@import('MyConfigA')
public class MyConfigB { ... }

How does Spring Data framework derive queries from method names?


Spring Data framework has an in-built query builder mechanism that derives queries based on the method name.

Method names are defines as 'find...By..','count...By...' etc. 'By' acts as the delimiter to identify the start of the criteria. 'And' and 'Or' are used to define multiple criteria. 'OrderBy' is used to identify the order by criteria.

findByFirstname(String firstName);
findByFirstnameAndLastname(String firstName, String lastName);
findByFirstnameAndLastnameOrderByFirstnameAcs(String firstName, string lastName);

What are the key interfaces and methods provided by the Spring framework to support data validations?


Spring framework provides the following interfaces and classes to support data validations.

Validator - Interface that defines methods to validate data objects.

Errors - Interface that defines methods to store and expose validation errors on a data object.

BindingResult - Interface that extends from Errors and represents binding results.

ValidationUtils - Utility class providing convenient methods for invoking a validator and for rejecting empty fields.



How do you implement a custom validator using String framework?


You can implement a custom validator by implementing the Validator interface and implementing the methods supports() and validate().

Supports(Class c) method takes an argument of type Class which defines the type of object that this validator will validate.

validate(Object o, Errors e) method takes in two arguments -
1. An argument of type Object that this validator will validate
2. An argument of type Errors which will store and expose the validation errors.


What is Aspect Oriented Programming (AOP)?


Aspect Oriented Programming is a programming methodology which aims to increase the modularity of the program by enabling separation of cross-cutting concerns.

Cross-cutting concerns refers to features or functions that apply across multiple functional areas.

Examples of cross-cutting concerns are logging and transaction management which cut across multiple types and objects.


What do you understand by Aspect, Join point, Advice, and Pointcut in AOP programming?


Aspects, Joins points, Advices, and Pointcuts are the core components of AOP.

Aspect - Aspect is a module that represents a cross-cutting concern.

Join point - Join point is a specific point in a running program, such as execution of a method or handling of an exception.

Advice - Advice specifies when the aspect acts at a particular join point - before, after, or around

Pointcut - Pointcut is an expression and a way to specify or match join points.


How does Spring framework support AOP?


Aspect Oriented Programming is one of the key components of Spring framework (Spring AOP).

Spring AOP is not a comprehensive framework such as AspectJ, rather it aims to solve common enterprise application problems by providing a simple integration between AOP implementation and Spring IoC.

Spring AOP provides the ability to develop custom aspects by either using XML-based approach or @AspectJ annotation approach, both of which utilize the AspectJ pointcut language.


What are the different types of advice provided by Spring AOP?


Spring AOP provides the following types of Advices.

Before advice - Advice that runs before a join point

After returning advice - Advice that runs if a join point completes normally without any exceptions

After throwing advice - Advice that runs if a join point exits with an exception.

After advice - Advice that runs irrespective of how the join point exits - normally or with exception.

Around advice - Advice that can run before and after join point.


How do you declare an Aspect using the XML-based approach and @AspectJ annotation approach?


Aspects in Spring AOP are regular Spring beans. Any Spring bean can be declared as an Aspect by decorating the bean either by XML-based configuration or by by AspectJ annotation.

In XML-based approach you can declare a bean as an aspect by using the element <aop:aspect>

In annotation based approach you can declare a bean as an aspect by using the AspectJ annotation @Aspect

//XML-based configuration
<aop:aspect id='myAspect' ref='myBean'>...</aop:aspect>
//Annotation based configuration
@Aspect
public class myBean {...}


How do you declare a Pointcut using the XML-based approach and @AspectJ annotation approach?


In XML-based approach you can declare a Pointcut by using the element <aop:pointcut> along with the pointcut expression.

In annotation based approacha you can declare a Pointcut by using the AspectJ annotation @Pointcut

//XML-based configuration
<aop:pointcut id='...' expression='...'>...</aop:pointcut>
//Annotation based configuration
@Pointcut('...')
public void myMethod() {...}

How do you declare an Advice using the XML-based approach and @AspectJ annotation approach?


Spring AOP provides five kinds of advices - before, after returning, after throwing, after, and around.

In XML-based approach you can declare these advices by using the elements <aop:before>, <aop:after-returning>, <aop:after-throwing>, <aop:after>, and <aop:around>.

In annotation based approach you can declare these advices by using the AspectJ annotations @Before, @AfterReturning, @AfterThrowing, @After, and @Around


What capabilities does Spring framework provide to support transactions?


Spring framework provides transaction management support having the following benefits and capabilities.

Consistent programming model that can be used across different transaction APIs - JTA, JPA, JDBC, Hibernate, etc.

Supports declarative and programmatic transaction management

Seamlessly integrates with Springs data access abstractions.


How do you make either all or some of the methods in a Spring class transactional using annotation-based approach?


You can make methods of a class to be transactional by applying the @Transactional annotation.

If you want all methods in the class to be transactional you can apply the annotation to the class.

If you want only some methods to be transactional you apply the annotation to each of the methods that are transactional.

In addition to annotating the class and methods, you have to annotate a configuration class (a class annotated with @Configuration annotation) with @EnableTransactionManagement annotation.


How do you implement DAOs using the annotation-approach with Spring framework DAO capabilities?


Spring framework provides convenient annotations that can be used for the implementation of the DAO.

Spring framework provides the @Repository annotation that can be applied to the DAO class. This annotation provides exception translation features, and configuration with out traditional XML entities for the DAOs.

Depending on the persistence technology used the persistence resources (example - JdbcTemplate and DataSource for JDBC, EntityManager for JPA, SessionFactory for Hibernate) can be dependency injected into the DAO.



Spring Data


What is Spring Data Framework?


Spring Data Framework is a Spring-based programming model for access to data.

Spring Data Framework has programming models or modules for accessing relataional databases, non-relational databases, map-reduce framewors and cloud-based data services.


What are some key modules provided in the Spring Data Framework?


Following are some key modules provided in Spring Data Framework.

Spring Data Commons - Core Spring data concepts that apply to all Spring data modules.

Spring Data JDBC - Contains Spring Data repository support for JDBC.

Spring Data JPA - Contains Spring Data repository support for JPA.

Spring MongoDBata KeyValue - Contains Spring Data repository support for key-value stores.

Spring Data LDAP - Contains Spring Data repository support for LDAP data sources.

Spring Data MongoDB - Contains Spring Data repository support for document-based MongoDB.

Spring Data Redis - Contains Spring Data repository support for Redis.

Spring Data Cassandra - Contains Spring Data repository support for Cassandra.

Spring Data Apache Solr - Contains Spring Data repository support for Apache Solr for Search based applications.


What are some key interfaces provided in the Spring Data Commons library?


The key interfaces provided in the Spring Data Commons library are Repository, CrudRepository and PagingAndSorting.

Repository - Repository is a marker interface which takes the entity class and the ID as type arguments.

CrudRepository CrudRepositiry extends from Repository, and adds technology-agnostic CRUD operations to the entity class.

Various technology-specific abstractions such as JpaRepository, MongoRepository etc. extend from CrudRepository and add capabilities of the underlying technology on top of the generic capabilities of the CrudRepository.

PagingAndSortingRepository - PagingAndSortingRepository extends from CrudRepository and adds paging and sorting capabilities to the entity.


What are some key methods defined in CrudRepository interface?


Some key methods defined in the Repository interface are save(S entity), findById(ID primaryKey), findAll(), long count(), void delete(T entity), boolean existsById(ID primaryKey).


What are key methods defined in PagingAndSortingRepository interface?


Key methods defined in the PagingAndSortingRepository interface are Iterable findAll(Sort sort), Page findAll(Pageable pageable).



How do you declare and use queries using Spring Data Framework?


You can declare queries on entities and use them in four steps.

1. Declare an interface extending from Repository, or one of its sub interfaces CrudRepository or PagingAndSortingRepository, passing the Entity type and ID as type parameters.

2. Declare the required query methods on the interface.

3. Configure Spring framework to create proxy instances for those interfaces.

4. Inject repository instance in a class and execute the query methods as needed.


How does Spring Data framework derive queries from method names?


Spring Data framework has an in-built query builder mechanism that derives queries based on the method name.

Method names are defined as 'find...By..','count...By...' etc. 'By' acts as the delimiter to identify the start of the criteria. 'And' and 'Or' are used to define multiple criteria. 'OrderBy' is used to identify the order by criteria.

findByFirstname(String firstName);
findByFirstnameAndLastname(String firstName, String lastName);
findByFirstnameAndLastnameOrderByFirstnameAcs(String firstName, string lastName);

How do you limit the number of query results based on method name?


The number of query results can be limited by using the keywords 'first' or 'top' followed by the number of desired results.

findFirst10ByLastname();

What is Spring Data JPA?


Spring Data JPA, a part of Spring Data framework, makes it easy to implement JPA based repositories.

Spring Data JPA makes it easier to implement data access layer to JPA repositories. Developers just need to declare repository interfaces, and Spring Data JPA will provide the implementation automatically.


How do you setup JPA repositories using XML_based configuration?


You setup JPA repositories using XML-based configuration using the element <jpa:repositories>.

<jpa:repositories base-package='com.interviewgrid.repositories'/>

How do you setup JPA repositories using JavaConfig based configuration?


You setup JPA repositories using JavaConfig based configuration by using the annotation @EnableJpaRepositories.

@EnableJpaRepositories
public class MyApplicationConfig() {...}

Spring Data JDBC


What support does Spring Data JDBC framework provide?


Spring Data JDBC, part of Spring Data, builds on top of the core repository support of Spring Data and provides support for JDBC repositories.

Spring Data JDBC aims at being a simple, limited, opinionated ORM. It does not implement many features of JPA such as caching and lazy loading.


What are the key features provided by Spring Data JDBC?


Following are some key features provided by Spring Data JDBC.

CRUD operations with customizable NamingStrategy

Support for @Query operations

JavaConfig based repository configuration using @EnableJdbcRepositories.


Spring Data MongoDB


What support does Spring Framework provide for MongoDB?


Spring Framework supports MongoDb as a part of the overall Spring Data Framework. Following are some of the support features for MongoDB

Provides Spring configuration support, both java-based as well as XML based, for MongoDB driver and MongoDB replica sets.

Provides a helper class - MongoTemplate, that helps with common MongoDB operations, and object mapping between documents and POJOs.

Translates MongoDB exceptions to Spring Data framework's Data Access Exception hierarchy.

Provides rich annotation-based Object mapping features.

Provides Java-based Query, Criteria and Update DSLs.


How do you connect to MongoDB using Spring Framework?


You connect to MongoDB using Spring framework by instantiating an instance of com.mongodb.client.MongoClient. This can be done either by using java-based configuration as well as by using XML-based configuration.

@Configuration
public class AppConfig {
 public @Bean MongoClient mongoClient() {
  return MongoClients.create('mongodb://localhost:27017');
 }
}

What are the key features of the MongoTemplate class provided by Spring Data Framework?


The MongoTemplate class is the key class provided by Spring Data MongoDB framework. It provides rich features to interact with MongoDb database. Following are some of the key features.

1. MongoTemplate class provides convenience operations to create, update, delete and query MongoDb databases. MongoTemplate class implements MongoOperations interface which provides methods similar to native MongoDB collections method names, such as - find(), findOne(), findAll(), findAndReplace(), insert(), save(), update() etc.

2. MongoTemplate class implements interface MongoConverter which facilitates mapping between domain objects and MongoDB documents.

3. MongoTemplate class translates MongoDb exceptions thrown by MongoDB driver to Spring Data Framework's Data Access Exception hierarchy.


How do you instantiate MongoTemplate?


MongoTemplate has multiple overloaded constructors that can be used to create an instance of MongoTemplate.

MongoTemplate(MongoClient mongoClient, String databaseName) - Takes MongoClient object and default database name.

MongoTemplate(MongoDatabaseFactory mongoFactory) - Takes a MongoDataBaseFactory object that encapsulates MongoClient, database, and its credentials.


How do you create, update and delete MongoDB documents using Spring Data MongoDB framework?


You can create, update and delete MongoDB documents using MongoTemplate, which provides convenience methods similar to native MongoDB collection methods.

insert(), update(), and remove() methods can be used to create, update and delete documents respectively.

MongoTemplate mongoTemplate = new MongoTemplate(MongoClients.create(), 'database');
//Create MongoDB document
Website w = new Website('interviewgrid','www.interviewgrid.com');
mongoTemplate.insert(w);
//find document
w = findById('interviewgrid',Website.class);
//update document
mongoTemplate.updateFirst(query(where('id')is('interviewgrid')),update('url','http://www.interviewgrid.com'), Website.class);
//delete document
mongoTemplate.remove(w);

What support does Spring Data JDBC framework provide?


Spring Data JDBC, part of Spring Data, builds on top of the core repository support of Spring Data and provides support for JDBC repositories.

Spring Data JDBC aims at being a simple, limited, opinionated ORM. It does not implement many features of JPA such as caching and lazy loading.


What are the key features provided by Spring Data JDBC?


Following are some key features provided by Spring Data JDBC.

CRUD operations with customizable NamingStrategy

Support for @Query operations

JavaConfig based repository configuration using @EnableJdbcRepositories.


Spring Web Flow


What is Spring Web Flow?

FAQ


Spring WebFlux


What is Spring WebFlux?



Spring RESTful Services


What annotation is used in Spring to make a class handle HTTP requests?


Spring builds RESTful web services through a class that handles HTTP requests. This class is called the controller class. Controller classes are identified by either the @Controller annotation or the @RestController annotation. In below example OrderController class is applied the @RestController annotation to make it a Spring RESTful web service controller.

@RestController
public class OrderController {
 ...
}

What annotation is used in Spring to map a HTTP request url to a controller method?


@RequestMapping is used to map a specific HTTP url to a controller method. In below example the method getOrder() handles the '/order' url request.

@RestController
public class OrderController {
 @RequestMapping('/order')
 public Order getOrder() {
  //return order;
 }
}

How do you limit a Spring controller method to handle only HTTP GET operation requests?


You can limit a Spring controller method to handle only HTTP GET operation requests by using parameter 'method=GET' in @RequestMapping annotation.

Alternatively you can use the @GetMapping annotation.

In below examples the method getOrder() handles the '/order' url request for HTTP GET operations only.

@RestController
public class OrderController {
 @RequestMapping(value='/order',method=GET)
 public Order getOrder() {
  //return order;
 }
}
@RestController
public class OrderController {
 @GetMapping(value='/order')
 public Order getOrder() {
  //return order;
 }
}

How do you bind HTTP request query string parameters to a controller method parameters?


The annotation @RequestParam is used to bind HTTP request query string parameters to controller method parameters.

In below example query string parameter 'orderId' is mapped to method parameter 'orderNumber'.

@RestController
public class OrderController {
 @RequestMapping(value='/order',method=GET)
 public Order getOrder(@RequestParameter(value='orderId') Integer orderNumber) {
  //return order;
 }
}

How do you bind HTTP request URI parameters to a controller method parameters?


The annotation @pathVariable is used to bind HTTP uri parameters to controller method parameters. In below example URI parameter 'orderId' is mapped to method parameter 'orderNumber'.

@RestController
public class OrderController {
 @RequestMapping(value='/order/{orderId}',method=GET)
 public Order getOrder(@PathVariable(value='orderId') Integer orderNumber) {
  //return order;
 }
}


How do you limit a Spring controller method to handle only HTTP POST operation requests?


You can limit a Spring controller method to handle only HTTP POST operation requests by using parameter 'method=POST' in @RequestMapping annotation.

Alternatively you can use the @PostMapping annotation.

In below examples the method newOrder() handles the '/order' url request for HTTP POST operations only.

@RestController
public class OrderController {
 @RequestMapping(value='/order',method=POST)
 public Order newOrder() {
  //return order;
 }
}
@RestController
public class OrderController {
 @PostMapping(value='/order')
 public Order newOrder() {
  //return order;
 }
}

How do you limit a Spring controller method to handle only HTTP PUT operation requests?


You can limit a Spring controller method to handle only HTTP PUT operation requests by using parameter 'method=PUT' in @RequestMapping.

Alternatively you can use the @PutMapping annotation.

In below example the method Order() handles the '/order' url request for HTTP PUT operations only.

@RestController
public class OrderController {
 @RequestMapping(value='/order',method=PUT)
 public Order newOrder() {
  //return order;
 }
}
@RestController
public class OrderController {
 @PutMapping(value='/order')
 public Order newOrder() {
  //return order;
 }
}

How do you bind the request body of HTTP POST or HTTP PUT request to an object?


The annotation @RequestBody is used to bind the request body of an HTTP POST or HTTP PUT request to an object. In below example the request body is mapped to the object 'Order'.

@RestController
public class OrderController {
 @RequestMapping(value='/order/{orderId}',method=PUT)
 public Order addOrder(@RequestBody Order order) {
  //return order;
 }
}

How do you bind an object to the HTTP Response of a HTTP Request?


The annotation @ResponseBody is used to bind an object to the HttpResponse.

On a controller having @Controller annotation a method has to be specifically annotated with @ResponseBody annotation in order to bind the returned object to the HttpResponse object.

On a controller having @RestController annotation a method need not be specifically annotated with @ResponseBody annotation since it is added by default.

Below examples show the handling of @ResponseBody annotation for @Controller annotated controller and @RestController annotated controller.

@RestController
public class OrderController {
 @RequestMapping(value='/order/{orderId}',method=PUT)
 public Order addOrder(@RequestBody Order order) {
  //return order;
 }
}
@Controller
public class OrderController {
 @RequestMapping(value='/order/{orderId}',method=PUT)
 @ResponseMapping
 public Order addOrder(@RequestBody Order order) {
  //return order;
 }
}

What is the difference between @ResponseBody and @ResponseEntity annotations?


@ResponseEntity represents an HTTP Response object including headers, response body and status. If you want to add headers to the response in addion to the body and status then use @ResponseEntity annotation.

@ResponseBody annotation represents only the response body of an HTTP Response object. When you use the annotation @ResponseBody on a controller method, the object returned from this method is bound to the response body of the HTTP Response object that is returned back to client.


Spring Security


What feature of Servlet API does Spring security use to provide security for Servlet applications?


Spring framework used the standard servlet Filter technology to provide security to Servlet based applications.


What is DelegatingFilterProxy?


DelegatingFilterProxy is a Servlet filter implementation provided by the Springframework that bridges the Servlet containers lifecycle and Spring framesorks's ApplicationContext. DelegatingFilterProxy delegates the work to a Spring bean that implements Filter.


What is FilterChainProxy?


FilterChainProxy is a Spring bean, that implements Filter, and contains Spring Security's servlet support. FilterChainProxy is wrapped in DelegatingFilterProxy, and delegates to security filters through SecurityFilterChain.


What is FilterChainProxy?


FilterChainProxy is a Spring bean, that implements Filter, and contains Spring Security's servlet support. FilterChainProxy is wrapped in DelegatingFilterProxy, and delegates to security filters through SecurityFilterChain.


What is SecurityFilterChain?


FilterChainProxy uses SecurityFilterChain to determine which security filters should be invokes for a particular request.



What are Security filters? What are some examples of security filters provided by the Spring framework?


Security filters are beans which extend Filter and register with FilterChainProxy via SecurityFilterChain.

Some common filters provided by SpringFramework are BasicAuthenticationFilter, BearerTokenAuthenticationFilter, DigestAuthenticationFilter, OAuth2LoginAuthenticationFilter, SessionManagementFilter, etc.


What are the key components provided by Spring framework to support Authentication?


Spring framework provides many key components to support Authentication features. These are.

SecurityContextHolder - Contains SecurityContext object, which has details of who is authenticated.

SecurityContext - Contains Authentication object, which has details of the current authenticated user.

Authentication - Contains the currently authenticated user - has fields principal, credentials and authorities


How do you set an authenticated user using Spring Security framework?


You set an authenticated user by creating the Authentication object with user details, setting the Authentication object in SecurityContext object, and then setting the SecurityContext object in SecurityContextHolder

SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication = new TestingAuthenticationToken('username', 'password', 'USER_ROLE');
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);

How do you access details of an authenticated user in Spring Security framework?


You access details of an authenticated user by getting the SecurityContext object from SecurityContextHolder object, and then getting the Authentication object from the SecurityContect object.

You can get the user name, principal and authorites granted for the user by calling corresponding methods on the Authentication object.

SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
String userName = authentication.getName();
Object principal = authentication.getPrincipal();
Collection authorities = authentication.getAuthorities();

What are GrantedAuthorities?


GrantedAuthorities are permissions or roles that the user is granted such as ROLE_ADMINISTRATOR, ROLE_SUPERVISOR etc.

These are set in the authorities fir=eld in the Authentication object, and can be retrieved by calling the method Authentication.getAuthorities()


What are the different authentication mechanisms supported by Spring framework?


Spring supports various authentication mechanisms - username and password, OAuth login, SAML login, JAAS, OpenId, X509 Authentication, etc.


What is OAuth 2.0 login mechanism?


The OAuth 2.0 login mechanism provides an application with the capability to have users login to the application by using their existing account at an OAuth 2.0 provider or OpenID Connect1.0 provider.

Example of these are applications that have the login feature 'Login With Google' or 'Login With Facebook'.

Some common OAuth 2.0 providers are Google, Facebook, Okta and Github.


What is SAML 2.0 login mechanism?


The SAML 2.0 login mechanism provides an application with the capability to have users login to the application by using their existing account at an SAML 2.0 provider

Some common SAML 2.0 providers are Okta and ADFS.


 
Subscribe to our Newsletter

 
 
RECOMMENDED RESOURCES
Behaviorial Interview
Top resource to prepare for behaviorial and situational interview questions.

STAR Interview Example