Spring Interview Questions and Answers
Practice Spring interview questions and answers organized by difficulty, with revealable explanations and related topics.
Entry questions
1 questions- Question 1Entry
What is Spring?
- Spring
Reveal answerHide answer
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based (Plain Old Java Object) programming model.
Junior questions
23 questions- Question 1Junior
What is the Model?
- Spring
Reveal answerHide answer
Model is a reference to encapsulate the data or output for rendering. Model is always created and passed to the view in Spring MVC. If a mapped controller method has Model as a method parameter, then a model instance is automatically injected by Spring framework to that method.
- Question 2Junior
What is the purpose of the Core Container module?
- Spring
Reveal answerHide answer
The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory , an implementation of the Factory pattern. The BeanFactory applies the Inversion of
Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code. - Question 2Junior
What are Spring beans?
- Spring
Reveal answerHide answer
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML definitions.
- Question 3Junior
What is a View and what's the idea behind supporting different types of View?
- Spring
Reveal answerHide answer
A View is an interface in Spring MVC application whose implementations are responsible for rendering context and exposing the model. A single view exposes multiple model attributes. Views in Spring MVC can be beans. They are likely to be instantiated as beans by a ViewResolver . As this interface is stateless, view implementations should be thread-safe. By using ViewResolver , a logical name of view can be resolved into different types of View implementation, e.g. JstlView for displaying JSP or other view implementations for FreeMarker and Velocity.
- Question 3Junior
Explain @RequestMapping annotation.
- Spring
Reveal answerHide answer
@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
- Question 4Junior
What is the DispatcherServlet and what is it used for?
- Spring
Reveal answerHide answer
The DispatcherServlet is an implementation of the Front Controller design pattern that handles all incoming web request to a Spring MVC application. A Front Controller pattern (see Enterprise application design pattern) is a common pattern in web applications whose job is to receive all request and route it to different components of the application for actual processing.
In Spring MVC, DispatcherServlet is used for finding the correct Controller to process a request, which it does with the help of handler mapping, e.g. the @RequestMapping annotation.
- Question 4Junior
How does the scope Prototype work?**
- Spring
Reveal answerHide answer
Scope prototype means that every time you call for an instance of the Bean, Spring will create a new instance and return it. This differs from the default singleton scope, where a single object instance is instantiated once per Spring IoC container.
- Question 5Junior
Do you need spring-mvc.jar in your classpath or is it part of spring-core?
- Spring
Reveal answerHide answer
The spring-mvc.jar is not part of spring-core, which means that if you want to use Spring MVC framework in your Java project, you must include spring-mvc.jar in your application's classpath. In a Java web application, spring-mvc.jar is usually placed inside the /WEB-INF/lib folder.
- Question 6Junior
What in the world are Spring beans?
- Spring
Reveal answerHide answer
Spring beans are just object instances that are managed by the Spring container, namely, they are created and wired by the framework and put into a "bag of objects" (the container) from where you can get them later. The "wiring" part there is what dependency injection is all about, what it means is that you can just say "I will need this thing" and the framework will follow some rules to get you the proper instance.
- Question 7Junior
What is Spring Boot?
- Spring
Reveal answerHide answer
Spring Boot is a project that provides a pre-configured set of frameworks to reduce boilerplate configuration so that you can have a Spring application up and running with the smallest amount of code.
- Question 8Junior
What is Spring Security?
- Spring
Reveal answerHide answer
Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks. To use Spring Security in web applications, you can get started with a simple annotation: @EnableWebSecurity.
- Question 9Junior
How to integrate Java Server Faces (JSF) with Spring?
- Spring
Reveal answerHide answer
JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We can integrate JSF and Spring in two ways: DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together. The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext. This allows one to easily inject dependencies into one's JSF-managed beans. FacesContextUtils: custom VariableResolver works well when mapping one's properties to beans in faces- config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()); - Question 10Junior
What do you mean by Bean wiring ?
- Spring
Reveal answerHide answer
The act of creating associations between application components (beans) within the Spring container is referred to as Bean wiring.
- Question 11Junior
What is Application Context?
- Spring
Reveal answerHide answer
On the surface, an application context is the same as a bean factory. Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides: A means for resolving text messages, including support for internationalization A generic way to load file resources Events to beans that are registered as listeners
- Question 12Junior
How is event handling done in Spring?
- Spring
Reveal answerHide answer
Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.
- Question 13Junior
What is Spring MVC framework?
- Spring
Reveal answerHide answer
The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
- Question 14Junior
Explain the @Controller annotation.
- Spring
Reveal answerHide answer
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.
- Question 15Junior
What are ORM's Spring supports?
- Spring
Reveal answerHide answer
Spring supports the following ORM's: Hibernate iBatis
JPA (Java Persistence API) TopLink JDO (Java Data Objects) OJB - Question 16Junior
What is default scope of bean in Spring framework?
- Spring
Reveal answerHide answer
The default scope of bean is Singleton for Spring framework.
- Question 17Junior
How do you provide configuration metadata to the Spring Container?
- Spring
Reveal answerHide answer
There are following three important methods to provide configuration metadata to the Spring Container − XML based configuration file. Annotation-based configuration
Java-based configuration
- Question 18Junior
What does a bean definition contain?
- Spring
Reveal answerHide answer
The bean definition contains the information called configuration metadata which is needed for the container to know the followings − How to create a bean Bean's lifecycle details Bean's dependencies
- Question 19Junior
What are the different modules in Spring framework?
- Spring
Reveal answerHide answer
Following are the modules of the Spring framework: Core module Bean module Context module Expression Language module JDBC module ORM module OXM module
Java Messaging Service(JMS) module Transaction module Web module Web-Servlet module Web-Struts module Web-Portlet module - Question 20Junior
What are benefits of using Spring?
- Spring
Reveal answerHide answer
Following is the list of few of the great benefits of using Spring Framework: Lightweight − Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB. Inversion of control (IOC) − Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects. Aspect oriented (AOP) − Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services. Container − Spring contains and manages the life cycle and configuration of application objects.
MVC Framework − Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks. Transaction Management − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example). Exception Handling − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
Mid questions
30 questions- Question 1Mid
What is Controller in Spring MVC framework?
- Spring
Reveal answerHide answer
Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.
- Question 2Mid
What are the differences between @RequestParam and @PathVariable?
- Spring
Reveal answerHide answer
Even though both @RequestParam and @PathVariable annotations are used to extract some data from URL, there is a key difference between them. The @RequestParam is used to extract query parameters, e.g. anything after "?" in the URL while the @PathVariable is used to extract the part of the URI itself. For example, if the given URL is http:
//localhost:8080/SpringMVC/books/3232233/?format=json then you can access the query parameter "format" using the @RequestParam annotation and /books/{id} usingthe @PathVariable , which will give you 3232233.
- Question 3Mid
What is the purpose of the session scope?
- Spring
Reveal answerHide answer
The purpose of the session scope is to create an instance of the bean for an HTTP Session. This means the same bean can serve multiple requests if it is scoped in session. You can define the scope of a Spring bean using scope attribute or the @Scope annotation in a Spring MVC application.
- Question 4Mid
Is the DispatcherServlet instantiated via an application context?
- Spring
Reveal answerHide answer
No, the DispatcherServlet is instantiated by Servlet containers like Tomcat or Jetty. You must define the DispatcherServlet into the web.xml file as shown below. You can see that load-on-startup tag is 1, which means DispatcherServlet is instantiated when you deploy the Spring MVC application to Tomcat or any other Servlet container. During instantiation, it looks for a file servlet- name-context.xml and then initializes beans defined in this file.
- Question 5Mid
What is the typical Bean life cycle in Spring Bean Factory Container?
- Spring
Reveal answerHide answer
Bean life cycle in Spring Bean Factory Container is as follows: The spring container finds the beans definition from the XML file and instantiates the bean. Using the dependency injection, spring populates all of the properties as specified in the bean definition If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans ID. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() , passing an instance of itself. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called. If an init-method is specified for the bean, it will be called. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
- Question 5Mid
Explain the difference between spring @Controller and @RestController annotation
- Spring
Reveal answerHide answer
@Controller is used to mark classes as Spring MVC Controller. @RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations
- Question 6Mid
How is the right View chosen when it comes to the rendering phase?
- Spring
Reveal answerHide answer
The right View is chosen by the ViewResolver in Spring MVC. When Controller returns a logical view name to DispatcherServlet, it consults to ViewResolver to find the right View. The ViewResolver , depending upon its implementation, resolves the logical view into a physical resource, e.g. a JSP page or a FreeMarker template.
- Question 6Mid
What is Spring IoC Container?
- Spring
Reveal answerHide answer
Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and makes it ready for our use. Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies. Some of the useful ApplicationContext implementations that we use are; AnnotationConfigApplicationContext : For standalone java applications using annotations based configuration. ClassPathXmlApplicationContext : For standalone java applications using XML based configuration. FileSystemXmlApplicationContext : Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system. AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
- Question 7Mid
Why are controllers testable artifacts?
- Spring
Reveal answerHide answer
In Spring MVC, Controllers are testable artifacts because they are not directly coupled with any View technology. They just return a logical View name, which can be easily tested.
- Question 7Mid
Does Spring Bean provide thread safety?
- Spring
Reveal answerHide answer
The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe. However, we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.
- Question 8Mid
How to handle exceptions in Spring MVC Framework?
- Spring
Reveal answerHide answer
Spring MVC Framework provides the following ways to help us achieving robust exception handling.
- Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
- Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
- HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
- Question 8Mid
Can we send an Object as the response of Controller handler method?
- Spring
Reveal answerHide answer
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
- Question 9Mid
How would you relate Spring MVC Framework to MVC architecture?
- Spring
Reveal answerHide answer
As the name suggests Spring MVC is built on top of Model-View-Controller architecture. DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller handler methods. The model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages. View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.
- Question 9Mid
What is the use of WebClient and WebTestClient?
- Spring
Reveal answerHide answer
WebClient is a component in the new Web Reactive framework that can act as a reactive client for performing non-blocking HTTP requests. Being a reactive client, it can handle reactive streams with back pressure, and it can take full advantage of Java 8 lambdas. It can also handle both sync and async scenarios. On the other hand, the WebTestClient is a similar class that we can use in tests. Basically, it’s a thin shell around the WebClient. It can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.
- Question 10Mid
How to validate form data in Spring Web MVC Framework?
- Spring
Reveal answerHide answer
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations. For custom validator implementation, we need to configure it in the controller class.
- Question 10Mid
What do you mean by Auto Wiring?
- Spring
Reveal answerHide answer
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes. no: This is default setting which means no autowiring. Explicit bean reference should be used for wiring. byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file. byType: It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the beans name in XML file. constructor: It injects the dependency by calling the constructor of the class. It has a large number of parameters. autodetect: First the container tries to wire using autowire by constructor, if it can’t then it tries to autowire by byType.
- Question 11Mid
What is Spring JDBCTemplate class and how to use it?
- Spring
Reveal answerHide answer
The Spring JDBC template is the primary API through which we can access database operations logic that we’re interested in: creation and closing of connections executing statements and stored procedure calls iterating over the ResultSet and returning results
- Question 11Mid
What is the difference between Bean Factory and Application Context?
- Spring
Reveal answerHide answer
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images. Application contexts can publish events to beans that are registered as listeners. Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances. MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable
- Question 12Mid
Name some of the Design Patterns used in the Spring Framework?
- Spring
Reveal answerHide answer
Singleton Pattern: Singleton-scoped beans
Factory Pattern: Bean Factory classes Prototype Pattern: Prototype-scoped beans Adapter Pattern: Spring Web and Spring MVC Proxy Pattern: Spring Aspect Oriented Programming support Template Method Pattern: JdbcTemplate, HibernateTemplate, etc. Front Controller: Spring MVC DispatcherServlet Data Access Object: Spring DAO support Model View Controller: Spring MVC
- Question 12Mid
What is Bean Factory?
- Spring
Reveal answerHide answer
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients. BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
- Question 13Mid
What is AOP?
- Spring
Reveal answerHide answer
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.
- Question 13Mid
Describe some of the standard Spring events
- Spring
Reveal answerHide answer
Spring provides the following standard events: ContextRefreshedEvent − This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface. ContextStartedEvent − This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event. ContextStoppedEvent − This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event. ContextClosedEvent − This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted. RequestHandledEvent − This is a web-specific event telling all beans that an HTTP request has been serviced.
- Question 14Mid
What is Aspect?
- Spring
Reveal answerHide answer
An Aspect is a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation ( @AspectJ style).
- Question 14Mid
Explain Bean lifecycle in Spring framework
- Spring
Reveal answerHide answer
Following is sequence of a bean lifecycle in Spring:
Instantiate − First the spring container finds the bean's definition from the XML file and instantiates the bean.. Populate properties − Using the dependency injection, spring populates all of the properties as specified in the bean definition. Set Bean Name − If the bean implements BeanNameAware interface, spring passes the bean's id to
setBeanName() method.Set Bean factory − If Bean implements BeanFactoryAware interface, spring passes the beanfactory to
setBeanFactory() method.Pre Initialization − Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method. Initialize beans − If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called. Post Initialization − If there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.Ready to use − Now the bean is ready to use by the application. Destroy − If the bean implements DisposableBean , it will call the destroy() method .
- Question 15Mid
What are the types of the transaction management Spring supports?
- Spring
Reveal answerHide answer
Spring supports two types of transaction management: Programmatic transaction management − This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
- Question 16Mid
What is bean auto wiring?
- Spring
Reveal answerHide answer
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory without using and elements.
- Question 17Mid
How can you inject Java Collection in Spring?
- Spring
Reveal answerHide answer
Spring offers four types of collection configuration elements which are as follows: − This helps in wiring i.e. injecting a list of values, allowing duplicates. − This helps in wiring a set of values but without any duplicates. − This can be used to inject a collection of name-value pairs where name and value can be of any type. − This can be used to inject a collection of name-value pairs where the name and value are both Strings.
- Question 18Mid
How do you define a bean scope?
- Spring
Reveal answerHide answer
When defining a in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.
- Question 19Mid
What is the difference between Bean Factory and ApplicationContext?
- Spring
Reveal answerHide answer
Following are some of the differences: Application contexts provide a means for resolving text messages, including support for i18n of those messages. Application contexts provide a generic way to load file resources, such as images. Application contexts can publish events to beans that are registered as listeners. Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
- Question 20Mid
What is Spring IoC container?
- Spring
Reveal answerHide answer
The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application. There are two types of IoC containers in Spring: Bean Factory container − This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications Spring ApplicationContext Container − This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
Senior questions
23 questions- Question 1Senior
What are the disadvantages of using Reactive Streams?
- Spring
Reveal answerHide answer
The major disadvantages of using reactive streams are: Troubleshooting a Reactive application is a bit difficult; be sure to check out our tutorial on debugging reactive streams for some handy debugging tips There is limited support for reactive data stores, as traditional relational data stores have yet to embrace the reactive paradigm There’s an extra learning curve when implementing
- Question 1Senior
Is Spring 5 compatible with older versions of Java?
- Spring
Reveal answerHide answer
In order to take advantage of Java 8 features, the Spring codebase has been revamped. This means older versions of Java cannot be used. Hence, the framework requires a minimum of Java 8.
- Question 2Senior
How is an incoming request mapped to a controller and mapped to a method?
- Spring
Reveal answerHide answer
Spring uses handler mappings to associate controllers with requests. Two of the commonly used handler mappings are BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping . In BeanNameUrlHandlerMapping , when the request URL matches the name of the bean, the class in the bean definition is the controller that will handle the request. On the other hand, in SimpleUrlHandlerMapping , the mapping is more explicit. You can specify the number of URLs and each URL can be explicitly associated with a controller. If you are using annotations to configure Spring MVC, which you should, then @RequestMapping annotations are used to map an incoming request to a controller and a handler method. You can also configure the @RequestMapping annotation by the URI Path, query parameters, HTTP methods of a request, and HTTP headers present in the request.
- Question 3Senior
What is the default scope in the web context?
- Spring
Reveal answerHide answer
The singleton scope is the default scope for a Spring bean, even in the web context. The other three web context-aware scopes are a request, session, and global-session, which are only available in a web application aware ApplicationContext object.
- Question 4Senior
What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?
- Spring
Reveal answerHide answer
@Component is used to indicate that a class is a component. These classes are used for auto-detection and configured as bean when annotation based configurations are used. @Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation. @Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes. @Service is used to indicate that a class is a Service. Usually, the business facade classes that provide some services are annotated with this.We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.
- Question 5Senior
What are some of the important Spring annotations you have used?
- Spring
Reveal answerHide answer
Some of the Spring annotations that I have used in my project are: @Controller – for controller classes in Spring MVC project. @RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples @ResponseBody – for sending Object as response, usually for sending XML or JSON data as response. @PathVariable – for mapping dynamic values from the URI to handler method arguments. @Autowired – for autowiring dependencies in spring beans. @Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present. @Service – for service classes. @Scope – for configuring scope of the spring bean. @Configuration, @ComponentScan and @Bean – for java based configurations. AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc.
- Question 6Senior
What is Spring MVC Interceptor and how to use it?
- Spring
Reveal answerHide answer
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion. We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter. We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too.
- Question 7Senior
How does Spring 5 integrate with JDK 9 modularity?
- Spring
Reveal answerHide answer
In Spring 5, everything has been modularized, thus we won’t be forced to import jars that may not have the functionalities we’re looking for.
- Question 8Senior
What bean scopes does Spring support? Explain them.
- Spring
Reveal answerHide answer
The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext. singleton − This scopes the bean definition to a single instance per Spring IoC container. prototype − This scopes a single bean definition to have any number of object instances. request − This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext. session − This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext. global-session − This scopes a bean definition to a global HTTP session. Only valid in the context of a web- aware Spring ApplicationContext.
- Question 9Senior
What is reactive programming?
- Spring
Reveal answerHide answer
Reactive programming is about non-blocking, event-driven applications that scale with a small number of threads, with back pressure being a key ingredient that aims to ensure producers don’t overwhelm consumers. The primary benefits of reactive programming are: increased utilization of computing resources on multicore and multi-CPU hardware and increased performance by reducing serialization Reactive programming is generally event-driven, in contrast to reactive systems, which are message-driven. Thus, using reactive programming does not mean we’re building a reactive system, which is an architectural style.
- Question 10Senior
What are Aspect, Advice, Pointcut, and JoinPoint in AOP?
- Spring
Reveal answerHide answer
Aspect: a class that implements cross-cutting concerns, such as transaction management Advice: the methods that get executed when a specific JoinPoint with matching Pointcut is reached in the application Pointcut: a set of regular expressions that are matched with JoinPoint to determine whether Advice needs to be executed or not JoinPoint: a point during the execution of a program, such as the execution of a method or the handling of an exception
- Question 11Senior
What is Aspect-Oriented Programming?
- Spring
Reveal answerHide answer
Aspects enable the modularization of cross-cutting concerns such as transaction management that span multiple types and objects by adding extra behavior to already existing code without modifying affected classes.
- Question 12Senior
What are some benefits of using Spring Transactions?
- Spring
Reveal answerHide answer
Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO Support declarative transaction management Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA Integrate very well with Spring’s various data access abstractions
- Question 13Senior
What is Join point?
- Spring
Reveal answerHide answer
A Joint Point represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.
- Question 14Senior
What are the advantages of Spring MVC over Struts MVC ?
- Spring
Reveal answerHide answer
Following are some of the advantages of Spring MVC over Struts MVC: Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance. Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests. Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface. In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy. Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet. Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend.
In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality. With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.
- Question 15Senior
What is Spring WebFlux?
- Spring
Reveal answerHide answer
Spring WebFlux is Spring’s reactive-stack web framework, and it’s an alternative to Spring MVC. In order to achieve this reactive model and be highly scalable, the entire stack is non-blocking.
- Question 15Senior
What are the limitations with autowiring?
- Spring
Reveal answerHide answer
Limitations of autowiring are: Overriding possibility − You can still specify dependencies using and settings which will always override autowiring. Primitive data types − You cannot autowire so-called simple properties such as primitives, Strings, and Classes. Confusing nature − Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
- Question 16Senior
What are the disadvantages of using Reactive Streams?
- Spring
Reveal answerHide answer
The major disadvantages of using reactive streams are: Troubleshooting a Reactive application is a bit difficult; be sure to check out our tutorial on debugging reactive streams for some handy debugging tips There is limited support for reactive data stores, as traditional relational data stores have yet to embrace the reactive paradigm There’s an extra learning curve when implementing
- Question 16Senior
What are different Modes of auto wiring?
- Spring
Reveal answerHide answer
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection − no − This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter. byName − Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. byType − Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown. constructor − Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. autodetect − Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
- Question 17Senior
What are the different types of Advices?
- Spring
Reveal answerHide answer
Different types of Advices in Spring AOP are: Before: These types of advices execute before the joinpoint methods and are configured using @Before annotation mark. After returning: These types of advices execute after the joinpoint methods completes executing normally and are configured using * AfterReturning annotation mark.
After throwing: These types of advices execute only if joinpoint method exits by throwing an exception and are configured using @AfterThrowing annotation mark.
After (finally): These types of advices execute after a joinpoint method, regardless of the method’s exitwhether normally or exceptional return and are configured using @After annotation mark. Around: These types of advices execute before and after a joinpoint and are configured using @Around annotation mark.
- Question 17Senior
What are inner beans in Spring?
- Spring
Reveal answerHide answer
A element inside the or elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes.
- Question 19Senior
What is the difference between concern and cross-cutting concern in Spring AOP?
- Spring
Reveal answerHide answer
Concern − Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns. Cross-cutting concern − It's a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.
- Question 20Senior
What is Weaving?
- Spring
Reveal answerHide answer
Weaving is the process of linking aspects with other application types or objects to create an advised object.
Expert questions
10 questions- Question 1Expert
What are the Mono and Flux types?
- Spring
Reveal answerHide answer
The WebFlux framework in Spring Framework 5 uses Reactor as its async foundation. This project provides two core types: Mono to represent a single async value, and Flux to represent a stream of async values. They both implement the Publisher interface defined in the Reactive Streams specification. Mono implements Publisher and returns 0 or 1 elements:
public abstract class Mono<T> implements Publisher<T> {...} Also_, Flux_ implementsPublisher and returns N elements:
public abstract class Mono<T> implements Publisher<T> {...}By definition, the two types represent streams, hence they’re both lazy, which means nothing is executed until we consume the stream using the
subscribe() method. Both types are immutable, therefore calling any methodwill return a new instance of Flux or Mono.
- Question 2Expert
What are some of the best practices for Spring Framework?
- Spring
Reveal answerHide answer
-
Avoid version numbers in schema reference, to make sure we have the latest configs.
-
Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
-
For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
-
Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
-
For application-level properties, the best approach is to create a property file and read it in the spring bean configuration file.
-
For smaller applications, annotations are useful but for larger applications, annotations can become a pain. If we have all the configuration in XML files, maintaining it will be easier.
-
Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
-
Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get usually added when you create projects through Spring Tool Suite templates.
-
If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
-
Use dependency injection when there is an actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.
- Question 2Expert
How does autowiring work in Spring?
- Spring
Reveal answerHide answer
First, and most important - all Spring beans are managed - they "live" inside a container, called "application context". Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el- resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener. Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context. What is "living" in the application context? This means that the context instantiates the objects, not you. I.e. - you never make new UserServiceImpl() - the container finds each injection point and sets an instance there.
- Question 4Expert
Explain the difference between context:annotation-config vs context:component-scan
- Spring
Reveal answerHide answer
context:annotation-config is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).
context:component-scan can also do what context:annotation-config does but context:component-scan also scans packages to find and register beans within the application context.
- Question 5Expert
What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?
- Spring
Reveal answerHide answer
@Inject is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6 (JSR-299). Spring has chosen to support using @Inject synonymously with their own @Autowired annotation. So, to answer your question, @Autowired is Spring's own (legacy) annotation. @Inject is part of a new Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-299 annotations in addition to their own.
- Question 6Expert
How does autowiring work in Spring?
- Spring
Reveal answerHide answer
First, and most important - all Spring beans are managed - they "live" inside a container, called "application context". Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el- resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener. Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context. What is "living" in the application context? This means that the context instantiates the objects, not you. I.e. - you never make new UserServiceImpl() - the container finds each injection point and sets an instance there.
- Question 7Expert
What are some of the valid return types of a controller method?
- Spring
Reveal answerHide answer
There are many return types are available for a controller method in Spring MVC, which is annotated by @RequestMapping inside the controller. Some of the popular ones are:
- String
- void
- View
4. ModelAndView (Class) 5. Model (Interface) 6. Map 7. HttpEntity or ResponseEntity 8. HttpHeadersEvery return type has its specific use. For example, if you are using String, then it means that the Controller will just return the View Name and this view name will be resolved by ViewResolver . If you don't want to return any view name, mention return type void. If you want to set a view name as well as want to send a object, use ModelAndView as a return type.
- Question 18Expert
Can we use both Web MVC and WebFlux in the same application?
- Spring
Reveal answerHide answer
As of now, Spring Boot will only allow either Spring MVC or Spring WebFlux, as Spring Boot tries to auto-configure the context depending on the dependencies that exist in its classpath. Also, Spring MVC cannot run on Netty. Moreover, MVC is a blocking paradigm and WebFlux is a non-blocking style, therefore we shouldn’t be mixing both together, as they serve different purposes.
- Question 19Expert
Where does the @Transactional annotation belong?
- Spring
Reveal answerHide answer
Transactions belong on the Service layer. It's the one that knows about units of work and use cases. It's the right answer if you have several DAOs injected into a Service that needs to work together in a single transaction.
- Question 20Expert
I want to know what actually happens when you annotate a method with @Transactional?
- Spring
Reveal answerHide answer
At a very high level, Spring creates proxies for classes that declare @Transactional on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism. Transactions in EJB work similarly, by the way. As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the "this" reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in [this forum post][3] in which I use a BeanFactoryPostProcessor to inject an instance of the proxy into "self- referencing" classes at runtime. I save this reference to a member variable called "me". Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. "me.someMethod()".) The forum post explains in more detail. Note that the BeanFactoryPostProcessor code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.