Spring All Questions
Spring All Questions
Spring All Questions
Spring handles all the infrastructure-related aspects which lets the programmer to
focus mostly on application development.
A Spring configuration file is basically an XML file that mainly contains the classes
information and describes how those classes are configured and linked to each
other. The XML configuration files are verbose and cleaner.
Spring container forms the core of the Spring Framework. The Spring container
uses Dependency Injection (DI) for managing the application components by
creating objects, wiring them together along with configuring and managing their
overall life cycles. The instructions for the spring container to do the tasks can be
provided either by XML configuration, Java annotations, or Java code.
5. What do you understand by Dependency Injection?
The main idea in Dependency Injection is that you don’t have to create your objects
but you just have to describe how they should be created.
They are the objects forming the backbone of the user’s application and are
managed by the Spring IoC container.
Spring beans are instantiated, configured, wired, and managed by IoC
container.
Beans are created with the configuration metadata that the users supply to
the container (by means of XML or java annotations configurations.)
There are 3 ways of providing the configuration metadata. They are as follows:
<bean id="interviewBitBean"
class="org.intervuewBit.firstSpring.InterviewBitBean">
<property name="name" value="InterviewBit"></property>
</bean>
Note: The last three scopes are available only if the users use web-aware
ApplicationContext containers.
The IoC container instantiates the bean from the bean’s definition in the XML
file.
Spring then populates all of the properties using the dependency injection
as specified in the bean definition.
The bean factory container calls setBeanName() which take the bean ID and
the corresponding bean has to implement BeanNameAware interface.
The factory then calls setBeanFactory() by passing an instance of itself (if
BeanFactoryAware interface is implemented in the bean).
If BeanPostProcessors is associated with a bean, then
the preProcessBeforeInitialization() methods are invoked.
If an init-method is specified, then it will be called.
Lastly, postProcessAfterInitialization() methods will be called if there
are any BeanPostProcessors associated with the bean that needs to be run
post creation.
11. What do you understand by Bean Wiring.
When beans are combined together within the Spring container, they are
said to be wired or the phenomenon is called bean wiring.
The Spring container should know what beans are needed and how the
beans are dependent on each other while wiring beans. This is given by
means of XML / Annotations / Java code-based configuration.
The IoC container autowires relationships between the application beans. Spring
lets collaborators resolve which bean has to be wired automatically by inspecting
the contents of the BeanFactory.
Different modes of this process are:
Spring Boot CLI – This allows you to Groovy / Maven for writing Spring boot
application and avoids boilerplate code.
Starter Dependency – With the help of this feature, Spring Boot aggregates
common dependencies together and eventually improves productivity and
reduces the burden on
Spring Initializer – This is a web application that helps a developer in
creating an internal project structure. The developer does not have to
manually set up the structure of the project while making use of this feature.
Auto-Configuration – This helps in loading the default configurations
according to the project you are working on. In this way, unnecessary WAR
files can be avoided.
Spring Actuator – Spring boot uses actuator to provide “Management
EndPoints” which helps the developer in going through the Application
Internals, Metrics etc.
Logging and Security – This ensures that all the applications made using
Spring Boot are properly secured without any hassle.
This enables the developer to use a single annotation instead of using multiple
annotations thus lessening the lines of code. However, Spring provides loosely
coupled features which is why we can use these annotations as per our project
needs.
19. What are the effects of running Spring Boot Application as “Java
Application”?
Spring Boot allows the developers to run the same application in different
environments by making use of its feature of external configuration. This
uses environment variables, properties files, command-line arguments, YAML
files, and system properties to mention the required configuration properties
for its corresponding environments. Following are the sources of external
configuration:
o Command-line properties – Spring Boot provides support for
command-line arguments and converts these arguments to properties
and then adds them to the set of environment properties.
o Application Properties – By default, Spring Boot searches for the
application properties file or its YAML file in the current directory of
the application, classpath root, or config directory to load the
properties.
o Profile-specific properties – Properties are loaded from
the application-{profile}.properties file or its YAML file. This file
resides in the same location as that of the non-specific property files
and the {profile} placeholder refers to an active profile or an
environment.
22. Can we change the default port of the embedded Tomcat server
in Spring boot?
23. Can you tell how to exclude any package without using the
basePackages filter?
@SpringBootApplication(exclude= {Student.class})
public class InterviewBitAppConfiguration {}
@EnableAutoConfiguration(exclude = {InterviewBitAutoConfiguration.class})
If the class is not specified on the classpath, we can specify the fully qualified name
as the value for the excludeName.
You can add into the application.properties and multiple classes can be
added by keeping it comma-separated.
25. Can the default web server in the Spring Boot application be
disabled?
@RequestMapping:
o This provides the routing information and informs Spring that any
HTTP request matching the URL must be mapped to the respective
method.
o org.springframework.web.bind.annotation.RequestMapping has to
be imported to use this annotation.
@RestController:
o This is applied to a class to mark it as a request handler thereby
creating RESTful web services using Spring MVC. This annotation adds
the @ResponseBody and @Controller annotation to the class.
o org.springframework.web.bind.annotation.RestController has to
be imported to use this annotation.
Before:
o This advice executes before a join point, but it does not have the
ability to prevent execution flow from proceeding to the join point
(unless it throws an exception).
o To use this, use @Before annotation.
AfterReturning:
o This advice is to be executed after a join point completes normally i.e
if a method returns without throwing an exception.
o To use this, use @AfterReturning annotation.
AfterThrowing:
o This advice is to be executed if a method exits by throwing an
exception.
o To use this, use @AfterThrowing annotation.
After:
o This advice is to be executed regardless of the means by which a join
point exits (normal return or exception encounter).
o To use this, use @After annotation.
Around:
o This is the most powerful advice surrounds a join point such as a
method invocation.
o To use this, use @Around annotation.
30. What are some of the classes for Spring JDBC API?
This can be done by using the query method of JdbcTemplate. There are two
interfaces that help to do this:
ResultSetExtractor:
o It defines only one method extractData that
accepts ResultSet instance as a parameter and returns the list.
o Syntax:
RowMapper:
o This is an enhanced version of ResultSetExtractor that saves a lot of
code.
o It allows to map a row of the relations with the instance of the user-
defined class.
o It iterates the ResultSet internally and adds it into the result collection
thereby saving a lot of code to fetch records.
33. What are the two ways of accessing Hibernate by using Spring.
Spring MVC is a request driven framework and one of the core components
of the Spring framework.
It comes with ready to use loosely coupled components and elements that
greatly aid developers in building flexible and robust web applications.
The MVC (Model - View - Controller) architecture separates and provides
loose coupling between the different aspects of the application – input logic
(Model), business logic (Controller), and UI logic (View).
37. What are the benefits of Spring MVC framework over other MVC
frameworks?
Spring MVC framework is built around a central servlet called DispatcherServlet that
handles all the HTTP requests and responses. The DispatcherServlet does a lot more
than that:
It seamlessly integrates with the IoC container and allows you to use each
feature of Spring in an easier manner.
The DispatcherServlet contacts HandlerMapping to call the appropriate
Controller for processing the request on receiving it. Then, the controller
calls appropriate service methods to set or process the Model data. The
service processes the data and returns the view name to DispatcherServlet.
DispatcherServlet then takes the help of ViewResolver and picks up the
defined view for the request. Once the view is decided, the DispatcherServlet
passes the Model data to View where it is finally rendered on the browser.
39. What is a View Resolver pattern and explain its significance in
Spring MVC?
Even though both these annotations are used to extract some data from
URL, there is a key difference between them.
o The @RequestParam is used to extract query parameters that is
anything after “?” in the URL.
o The @PathVariable is used to extract the data present as part of the
URI itself.]
o For example, if the given URL is
http://localhost:8080/InterviewBit/Spring/SpringMVC/?format=json,
then you can access the query parameter “format” using the
@RequestParam annotation and /Spring/{type} using the
@PathVariable, which will give you SpringMVC.
@RequestMapping("/Spring/{type}")
public void getQuestions(@PathVariable("type") String type,
@RequestParam(value = "format", required = false)
String format){
/* Some code */
}
The annotation plays a very important role in binding method parameters to the
respective attribute that corresponds to a model. Then it reflects the same on the
presentation page. The role of the annotation also depends on what the developer
is using that for. In case, it is used at the method level, then that method is
responsible for adding attributes to it. When used at a parameter level, it represents
that the parameter value is meant to be retrieved from the model layer.
web.xml is also known as the Deployment Descriptor which has definitions of the
servlets and their mappings, filters, and lifecycle listeners. It is also used for
configuring the ContextLoaderListener. Whenever the application is deployed, a
ContextLoaderListener instance is created by Servlet container which leads to a load
of WebApplicationContext.
Construction-Based:
o This type of DI is accomplished when the Spring IoC (Inversion of
Control) container invokes parameterized constructor having a
dependency on other classes.
o This cannot instantiate the values partially and ensures that the
dependency injection is done fully.
o There are two possible ways of achieving this:
Annotation Configuration: This approach uses POJO objects and annotations for
configuration. For example, consider the below code snippet:
@Configuration
@ComponentScan("com.interviewbit.constructordi")
public class SpringAppConfig {
@Bean
public Shape shapes() {
return new Shapes("Rectangle");
}
@Bean
public Dimension dimensions() {
return new Dimension(4,3);
}
}
Here, the annotations are used for notifying the Spring runtime that the class
specified with @Bean annotation is the provider of beans and the process of context
scan needs to be performed on the package com.interviewbit.constructordi by
means of @ComponentScan annotation. Next, we will be defining a Figure class
component as below:
@Component
public class Figure {
private Shape shape;
private Dimension dimension;
@Autowired
public Figure(Shape shape, Dimension dimension) {
this.shape = shape;
this.dimension = dimension;
}
}
Spring encounters this Figure class while performing context scan and it initializes
the instance of this class by invoking the constructor annotated with @Autowired.
The Shape and Dimension instances are obtained by calling the methods annotated
with @Bean in the SpringAppConfig class. Instances of Engine and Transmission will
be obtained by calling @Bean annotated methods of the Config class. Finally, we
need to bootstrap an ApplicationContext using our POJO configuration:
XML Configuration: This is another way of configuring Spring runtime by using the
XML configuration file. For example, consider the below code snippet in the
springAppConfig.xml file:
Setter-Based:
o This form of DI is achieved when the Spring IoC container calls the
bean’s setter method after a non-parameterized constructor is called
to perform bean instantiation.
o It is possible to achieve circular dependency using setter injection.
o For achieving this type of DI, we need to configure it through the
configuration file under the <property> tag. For example, consider a
class InterviewBit that sets the property articles as shown below:
package com.interviewbit.model;
import com.interviewbit.model.Article;
public class InterviewBit {
// Object of the Article interface
Article article;
public void setArticle(Article article)
{
this.article = article;
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="InterviewBit" class="com.interviewbit.model.InterviewBit">
<property name="article">
<ref bean="JsonArticle" />
</property>
</bean>
<bean id="JsonArticle" class="com.interviewbit.bean.JsonArticle" />
</beans>
The ‘JsonArticle’ bean is injected into the InterviewBit class object by means of
the setArticle method.
In cases where both types of dependencies are used, then the setter dependency
injection has more preference by considering the specificity nature.
@Component
@Scope("session")
public class UserBean {
//some methods and properties
}
Using @SessionScope:
@Component
@SessionScope
public class UserBean {
//some methods and properties
}
The annotation is used for indicating that the property of the bean should be
populated via autowiring or any explicit value during the bean definition at the
configuration time. For example, consider a code snippet below where we need to
have the values of age and the name:
import org.Springframework.beans.factory.annotation.Required;
public class User {
private int age;
private String name;
@Required
public void setAge(int age) {
this.age = age;
}
public Integer getAge() {
return this.age;
}
@Required
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
No, the singleton beans are not thread-safe because the concept of thread-safety
essentially deals with the execution of the program and the singleton is simply a
design pattern meant for the creation of objects. Thread safety nature of a bean
depends on the nature of its implementation.
The thread safety can be achieved by changing the scope of the bean to request,
session or prototype but at the cost of performance. This is purely based on the
project requirements.
<servlet-mapping>
<servlet-name>InterviewBitServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
57. How does the Spring MVC flow look like? In other words, How
does a DispatcherServlet know what Controller needs to be called
when there is an incoming request to the Spring MVC?
58. Where does the access to the model from the view come from?
The view requires access to the model to render the output as the model contains
the required data meant for rendering. The model is associated with the controller
that processes the client requests and finally encapsulates the response into the
Model object.
@PostMapping("/interviewbit")
public String registerCourse(@Valid RegisterUser registerUser,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "home";
}
model.addAttribute("message", "Valid inputs");
return "home";
}
The Spring will understand to find the corresponding validators by checking the
@Valid annotation on the parameter.
Spring Interceptors are used to pre-handle and post-handle the web requests in
Spring MVC which are handled by Spring Controllers. This can be achieved by
the HandlerInterceptor interface. These handlers are used for manipulating the
model attributes that are passed to the controllers or the views.
The Spring handler interceptor can be registered for specific URL mappings so that
it can intercept only those requests. The custom handler interceptor must
implement the HandlerInterceptor interface that has 3 callback methods that can
be implemented:
preHandle()
postHandle()
afterCompletion()
The only problem with this interface is that all the methods of this interface need to
be implemented irrespective of its requirements. This can be avoided if our handler
class extends the HandlerInterceptorAdapter class that internally implements
the HandlerInterceptor interface and provides default blank implementations.
63. How is the form data validation done in Spring Web MVC
Framework?
Spring MVC does the task of data validation using the validator object which
implements the Validator interface. In the custom validator class that we have
created, we can use the utility methods of the ValidationUtils class
like rejectIfEmptyOrWhitespace() or rejectIfEmpty() to perform validation of the
form fields.
@Component
public class UserValidator implements Validator
{
public boolean supports(Class clazz) {
return UserVO.class.isAssignableFrom(clazz);
}
In the fields that are subject to validation, in case of errors, the validator methods
would create field error and bind that to the field.
<context:component-scan base-package="com.interviewbit.validators"/>
OR
The validator class can be registered in the context file directly as a bean as shown:
@Autowired
private ServletContext servletContext;
@Autowired
private ServletConfig servletConfig;
BeanFactory and the ApplicationContext are both Java interfaces. The difference is
that the ApplicationContext extends the BeanFactory. BeanFactory provides both
IoC and DI basic features whereas the ApplicationContext provides more advanced
features. Following are the differences between these two:
Syntax:
<bean
id="localeResolver"class="org.Springframework.web.servlet.i18n.SessionLoca
leResolver">
<property name="defaultLocale" value="en" />
</bean>
Syntax:
<bean
id="localeChangeInterceptor"class="org.Springframework.web.servlet.i18n.Lo
caleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
Syntax:
<bean
class="org.Springframework.web.servlet.mvc.annotation.DefaultAnnotationHan
dlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
The MultipartResolver is used for handling the file upload scenarios in the Spring
web application. There are 2 concrete implementations of this in Spring, they are:
CommonsMultipartResolver meant for Jakarta Commons FileUpload
StandardServletMultipartResolver meant for for Servlet 3.0 Part API
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/MySQLDB"/>
</bean>
69. What will be the selection state of a checkbox input if the user
first checks the checkbox and gets validation errors in other fields
and then unchecks the checkbox after getting the errors?
The validation is generally performed during HTTP POST requests. During HTTP
requests, if the state of the checkbox is unchecked, then HTTP includes the request
parameter for the checkbox thereby not picking up the updated selection. This can
be fixed by making use of a hidden form field that starts with _ in the Spring MVC.
1.