Core Java

Spring Interview Questions

Java Interview

”Here I cover  Spring Interview Questions which are most frequently asked and most important for advance java interview.


Q1. What is Spring Framework?

Spring is really important and an open source development tool for Java. 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. The main purpose of spring framework is to make Java easier to use and implement the program. In normal programming, we use a bunch of classes and passing from one place to another place which makes your program complicated. But when you use spring framework, it has one bag of beans and each and every bean declare their dependencies so spring container resolved their requirements automatically.

Q2. What are some of the important features of Spring Framework?

First, an important feature of spring framework is Lightweight. Lightweight means not in weight but in terms of size and transparency. The basic version of spring framework is around 2MB which is small in size and also very transparent.

Second, an important feature of spring framework is Inversion of control (IOC): Spring use Inversion of control to loose coupling. The objects give their dependencies instead of creating or looking for dependent objects.

Third, an important feature of spring framework is Aspect-oriented (AOP): Aspect-oriented programming use to enables cohesive development by separating application business logic from system services.

Fourth, an important feature of spring framework is Container: Spring container manages the life cycle and configuration of application objects.

Fifth, important feature of spring framework is MVC Framework: Spring provides a well-designed MVC framework, and it provides a great alternative to web frameworks which are easier to use and implement. For example, Struts or other over engineered or less popular web frameworks.

Sixth, an important feature of spring framework is Exception Handling: Spring provides a convenient API which translates technology-specific exceptions into consistent, unchecked exceptions.

Q3. What are some advantages of Spring Framework?

It reduced the direct dependencies between different components of the application. For example, Spring IoC container is responsible for initializing resources and inject them as dependencies.

It provides to write unit test cases for business because business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.

It reduces the total amount of boiler-plate code. I like JDBCTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.

Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need one particular feature, we don’t need to add that in our project.

Q4. What do you understand by Dependency Injection?

First of all dependency Injection is only one concrete example of Inversion of Control(IOC).

In this concept, you don’t need to create your objects but you have described how they are created. You don’t need to connect your components or services directly in code but you have to describe which services are needed by which components in a configuration file. After that IOC containe is then responsible for hooking it all up.

It allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile time to runtime.

Q5. What do you understand by Aspect Oriented Programming?

In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented programming.

Q6. What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?

Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using Aspect annotation.

Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that get executed when a specific join point with matching pointcut is reached in the application. You can think of Advice as Spring interceptors or Servlet Filters.

Pointcut: Pointcut is regular expressions that are matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.

Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join point is always the execution of a method.

Advice Arguments: We can pass arguments in the advice methods. We can use the args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where argument type is determined.

Q7. What is Spring IoC Container?

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.

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.

Q8. What is a Spring Bean?

Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance.

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 <bean/> definitions.

Q9. What are different ways to configure a class as Spring Bean?

There are three different ways to configure Spring Bean.

XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:

<bean name=”myBean” class=”com.journaldev.spring.beans.MyBean”></bean>

Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean This annotation is used with @Configurationclasses to configure a spring bean. Sample configuration is:

@Configuration

@ComponentScan(value=”com.journaldev.spring.main”)

public class MyConfiguration {

@Bean

public MyService getService(){

return new MyService();

}

}

To get this bean from spring context, we need to use following code snippet:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfiguration.class);

MyService service = ctx.getBean(MyService.class);

Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes. For example:

<context:component-scan base-package=”com.journaldev.spring” />

Q10. How to get ServletContext and ServletConfig object in a Spring Bean?

There are two ways to get Container specific objects in the spring bean.

First one is implementing Spring Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces.

The second one is using @Autowiredannotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.

@Autowired

ServletContext servletContext;

Q11. What are Bean wiring and @Autowired annotation?

The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.

Usually, it’s best practice to do the explicit wiring of all the bean dependencies, but spring framework also supports autowiring. We can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable annotation-based configuration in spring bean configuration file. This can be done by context:annotation-config element.

Q12. What is a Controller in Spring MVC?

Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.

A Controller class is responsible for handling a different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually, it’s used with @RequestMapping annotation to define handler methods for specific URI mapping.

Q13. What’s the difference between @Component, @Repository & @Service annotations in Spring?

@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 a 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.

Q14. How to handle exceptions in Spring MVC Framework?

Spring MVC Framework provides 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.

Q15. How to create ApplicationContext in a Java Program?

AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.

ClassPathXmlApplicationContext: If we have spring bean configuration XML file in the standalone application, then we can use this class to load the file and get the container object.

FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the XML configuration file can be loaded from anywhere in the file system.

Q16. What is ContextLoaderListener?

ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to all other contexts.

Q17. What are the minimum configurations needed to create Spring MVC application?

For creating a simple Spring MVC application, we would need to do following tasks.

Add spring-context and spring-webmvc dependencies in the project.

Configure DispatcherServletin the web.xml file to handle requests through spring container.

Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also, we need to configure view resolver for view pages.

Controller class with request mappings defined to handle the client requests.

Q18. How to validate form data in Spring Web MVC Framework?

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.

 Q19. What is Spring JdbcTemplate class and how to use it?

Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid bolier-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement etc.

Q20. How would you achieve Transaction Management in Spring?

Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is very easy to use that’s why it is most widely used.

We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure transaction manager for the DataSource in the spring bean configuration file.

Q21. What is Spring Security?

Spring security framework focuses on providing both authentication and authorization in java applications. It also takes care of most of the common security vulnerabilities such as CSRF attack.

It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such as @EnableWebSecurity.

Q22. How to inject a java.util.Properties into a Spring Bean?

We need to define property Configure bean that will load the properties from the given property file. Then we can use Spring EL support to inject properties into other bean dependencies.

If you are using annotation to configure the spring bean, then you can inject property like below.

@Value(“${maxReadResults}”)

private int maxReadResults;