Java-Spring-Interview-Questions-and-Answers-LearnoVita

Java Spring Interview Questions and Answers

Last updated on 27th Sep 2020, Blog, Interview Question

About author

Anwar (Sr Technical Project Manager )

He is a Proficient Technical Expert for Respective Industry Domain & Serving 11+ Years. Also, Dedicated to Imparts the Informative Knowledge's to Freshers. He Share's this Blogs for us.

(5.0) | 15624 Ratings 1050

Currently, we have Spring Framework 5.0 in trend, which was a major release after Spring 4. Spring Framework 5.0 has features like Reactive Programming Model, Functional Support with Kotlin, Library Support, etc. Reactive Programming is a major achievement by the Spring team. Soon, projects will start implementing the reactive features.

1. What is Spring?

Ans:

It is a lightweight, loosely coupled and integrated framework for developing enterprise applications in java

2. What are the advantages of spring framework?

Ans:

  1. 1. Predefined Templates
  2. 2. Loose Coupling
  3. 3. Easy to test
  4. 4. Lightweight
  5. 5. Fast Development
  6. 6. Powerful Abstraction
  7. 7. Declarative support

3. What are the modules of spring framework?

Ans:

  1. 1. Test
  2. 2. Spring Core Container
  3. 3. AOP, Aspects and Instrumentation
  4. 4. Data Access/Integration
  5. 5. Web

4. What is CSRF?

Ans:

Cross-Site Request Forgery (CSRF) is a security attack where a fraudulent website tricks the user into performing an event on the web application that he/she is logged into. For instance, if the user is logged into the online banking account, this attack tricks the user into transferring the money to an unknown person.

5. What is the role of IOC containers in spring?

Ans:

IOC container is responsible to:

  •  create the instance
  • configure the instance, and
  • assemble the dependencies

6.  What are the types of IOC containers in spring?

Ans:

There are two types of IOC containers in spring framework.

  • BeanFactory
  • ApplicationContext

7. What is the difference between BeanFactory and ApplicationContext?

Ans:

BeanFactory is the basic container whereas ApplicationContext is the advanced container. ApplicationContext extends the BeanFactory interface. ApplicationContext provides more facilities than BeanFactory such as integration with spring AOP, message resource handling for i18n etc.

8. What is the difference between constructor injection and setter injection?

Ans:

Constructor InjectionSetter Injection

 No Partial Injection

Partial Injection
Does Not override the setter propertyOverrides the constructor property if both are defined.
Creates new instance if any modification occursDoesn’t create new instance if you change the property value
Better for too many propertiesBetter for a few properties.

9. What is autowiring in spring? What are the autowiring modes?

Ans:

Autowiring enables the programmer to inject the bean automatically. We don’t need to write explicit injection logic.

Let’s see the code to inject beans using dependency injection.

  • <bean id=”emp” class=”com.javatpoint.Employee” autowire=”byName” />  

The autowiring modes are given below:

ModeDescription

no

this is the default mode, it means autowiring is not enabled.
byNameinjects the bean based on the property name. It uses a setter method.
byTypeinjects the bean based on the property type. It uses a setter method.
constructorIt injects the bean using constructor

The “autodetect” mode has been deprecated since spring 3.

10. What are the different bean scopes in spring?

Ans:

There are 5 bean scopes in spring framework.

ScopeDescription
singletonThe bean instance will be only once and the same instance will be returned by the IOC container. It is the default scope.
prototypeThe bean instance will be created each time when requested.
requestThe bean instance will be created per HTTP request.
sessionThe bean instance will be created per HTTP session.
globalsessionThe bean instance will be created per HTTP global session. It can be used in portlet context only.
Subscribe For Free Demo

Error: Contact form not found.

11.  In which scenario, you will use singleton and prototype scope?

Ans:

Singleton scope should be used with EJB stateless session bean and prototype scope with EJB stateful session bean.

12. What are the transaction management supports provided by spring?

Ans:

Spring framework provides two type of transaction management supports:

  1. 1. Programmatic Transaction Management: should be used for few transaction operations.
  2. 2. Declarative Transaction Management: should be used for many transaction operations.

13. What are the advantages of JdbcTemplate in spring?

Ans:

Less code: By using the JdbcTemplate class, you don’t need to create connection,statement,start transaction,commit transaction and close connection to execute different queries. You can execute the query directly.

14. What are classes for the spring JDBC API?

Ans:

  1. 1. JdbcTemplate
  2. 2. SimpleJdbcTemplate
  3. 3. NamedParameterJdbcTemplate
  4. 4. SimpleJdbcInsert
  5. 5. SimpleJd

15. How can you fetch records by spring JdbcTemplate?

Ans:

You can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:

  1. 1. ResultSetExtractor
  2. 2. RowMapper

16. What is the advantage of NamedParameterJdbcTemplate?

Ans:

NamedParameterJdbcTemplate class is used to pass value to the named parameter. A named parameter is better than ? (question mark of PreparedStatement).

17. What is the advantage of SimpleJdbcTemplate?

Ans:

The SimpleJdbcTemplate supports the feature of var-args and autoboxing.

18. What is AOP?

Ans:

AOP is an acronym for Aspect Oriented Programming. It is a methodology that divides the program logic into pieces or parts or concerns.

It increases the modularity and the key unit is Aspect.

19. What are the advantages of spring AOP?

Ans:

AOP enables you to dynamically add or remove concern before or after the business logic. It is pluggable and easy to maintain.

20. What are the AOP terminologies?

Ans:

AOP terminologies or concepts are as follows:

  • JoinPoint
  • Advice
  • Pointcut
  • Aspect
  • Introduction
  • Target Object
  • Interceptor
  • AOP Proxy
  • Weaving

21. What is JoinPoint?

Ans:

JoinPoint is any point in your program such as field access, method execution, exception handling etc.

22. What is Tight Coupling?

Ans:

When a class (ClassA) is dependent on another class’s object (ClassB), then we say ClassA is “tightly” Coupled with ClassB. Spring helps us to create classes in a way that Tight Coupling can be removed and Loose Coupling can be done.

23. What is Loose Coupling?

Ans:

Loose Coupling removes the dependency of an object (ClassB) on a class (ClassA). Loose Coupling is approached by creating an interface and a setter & getter method, or by using a constructor which takes the interface object.

24. What are Beans in Spring?

Ans:

When a class is annotated or decorated using the @Component, such a class is called a Bean in Spring. Beans are maintained by Application Context.

25. Explain Bean creation process?

Ans:

The process of Bean creation has the following phases

(i)  Starts with a class (c1) which has the annotation @Component.

(ii)  Checks if the component annotated class (c1) is dependent.

(iii)  If yes, then Spring will create a bean for that class (c2) too.

(iv)  A connection or autowiring will occur between the two classes (c1 and c2) using @Autowired annotation and also through the constructor (c2) or the default case setClass Function (interface the Interface).

26. What is the importance of the annotation @Primary

Ans:

This annotation is used on a class that needs to be taken by spring on a primary basis. For instance, if ClassX is @Component annotated and is dependent on both Class1 and Class2 (both @Component annotated) then the compiler would report an error. To show the primary class between Class1 and Class2 we use @Primary.

27. What is Dependency Injection?

Ans:

Dependency Injection is where Spring searches for beans; once the appropriate bean is found, it autowired the bean to the dependent class. Dependency Injection is the process where Spring framework looks for the beans and identifies the dependencies, and creates the instances of beans and @autowired them.

28. Explain Inversion of Control (IOC).

Ans:

In Tight Coupling the dependent class takes the responsibility of creating its dependency. Whereas, in Loose Coupling, we use @Autowired annotation over the dependency class (or reference) and Spring takes control of creating the instance and injects the dependency.

29. What are the roles of an IOC (Inversion of Control) Container?

Ans:

IOC Container does the following things-

           (i) Find Beans

           (ii) Identify their dependencies and wire the dependencies

           (iii) Manage Lifecycle of the Bean (creation, processing, and destruction)

30. What is Application Context?

Ans:

It is an advanced version of IOC Container. It provides all the functionalities of Bean Factory and also provides things like AOP, Internationalization capabilities, web application context (request, session, etc).

Course Curriculum

Enhance Your Career with Java Spring Training from Real Time Experts

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

31. Explain the process of creating an ApplicationContext in Spring.

Ans:

The ApplicationContext can be defined in two ways (i) using XML, (ii) using @Configuration. Once the configuration is done in any of the ways defined above, the ApplicationContext is created using new ClassPathXmlApplicationContext. The ClassPathXmlApplicationContext looks for the XML files, using this is one of the two ways. The other way is to use AnnotationConfigApplicationContext.

32. Explain Component Scan.

Ans:

Component Scan is one method of asking Spring to detect Spring-managed components, the input for this search is the packages. Two methods are available to define a Component Scan-

(i) Java Configuration; wherein, we use the @Component annotation to which we specify all the packages, for which Spring does the search.

(ii) XML Configuration- we use <context:component-scan base-package=”com.demo.compscanex”/>

33. How do you perform the same (above question) in Spring Boot?

Ans:

In Spring Boot the annotation used to perform the scan is @SpringBootApplication. This annotation on a class would automatically initiate the component scan on the package where they are in.

34. Differentiate @Component, @Repository and @Service and @Controller?

Ans:

Typically a web application is developed in layers like the controller (which is the initial point of client communication), business (where the actual code or logic of the application is written) and DAO (where the database connections and interaction happens). In such an architecture web application, @Component can be used in any of the layers. Whereas, the @Controller is used in the controller/web layer. @Service is used in the business layer and @Repository is used in the DAO layer.

35. List out the different scopes of Bean.

Ans:

      (i) Singleton: throughout the spring context only one instance is created.

      (ii) Prototype: a new bean is created whenever requested.

      (iii) Request: Every HTTP Request creates a bean.

      (iv) Session: A bean for every HTTP Session.

36. List out the types of Dependency Injection.

Ans:

The types of Dependency Injection-

            (i) Setter Injection and (ii) Constructor Injection.

37. What is the difference between the Configuration types XML and Annotation?

Ans:

These are the two ways of setting up the configuration, and they perform in the say way. Though, when the annotation approach is taken, very less amount of code is written and the result would be the same as compared to the XML approach.

38. List out the ways Autowiring is done.

Ans:

       (i) byType

       (ii) byName

       (iii) Constructor (same as byType, but through constructor)

39. What is Dirty Read?

Ans:

When a transaction (t1) is meant to read the changes that are performed by another transaction (t2) and provided transaction t2 is not committed yet; then in such a situation, the transaction t1 is called Dirty Read transaction.

40. List out the new features available in Spring Framework 4.0 and Spring Framework 5.0?

Ans:

Spring 4.0 is the first to support Java features. Spring 5.0 has the support for Reactive Programming and Kotlin.

41. What is a FrontController?

Ans:

In FrontController, the Servlet will not get the first request; the first request would go to FrontController and the request is passed on to the right servlet. In other words, DispatcherServlet is the front controller which intercepts all the requests from the client and then dispatches to appropriate controllers.

42. What is a ViewResolver?

Ans:

ViewResolver enables a web application to select its view (such as JSP) dynamically. ViewResolver gets a name which is appended by /WEB-INF/views and a .jsp. All the display on the content is done in an HTML page.

43. List out all the concepts that are available in the MVC Architecture?

Ans:

  1. 1. The browser sends a request to DispatcherServlet
  2. 2. DispatcherServlet knows the HanderMapping and can find the appropriate controllers
  3. 3. Controllers execute the request and put the data in the model and return back the view name to the DispatcherServlet.
  4. 4. DispatcherServlet uses the view name and ViewResolver to map to the view.

44. Explain Model Attribute?

Ans:

The annotation @ModelAttribute is decorated on a method typically present inside a Controller. This will help the method to be available in all other methods available in the controller.

45. What is a Session Attribute?

Ans:

The annotation @SessionAttributes (“argument”) is decorated on class (Controller). The attribute (argument) that is present in Model is available in the session.

46.How do we implement DI in Spring Framework?

Ans:

We can use Spring XML based as well as Annotation-based configuration to implement DI in spring applications. For better understanding, please read the Spring Dependency Injection example where you can learn both the ways with JUnit test case. The post also contains a sample project zip file, that you can download and play around to learn more.

47. What are the new features in Spring 5?

Ans:

Spring 5 brought a massive update to the Spring framework. Some of the new features in Spring 5 are:

  • Spring 5 runs on Java 8+ and supports Java EE 7. So we can use lambda expressions and Servlet 4.0 features. It’s good to see Spring trying to support the latest versions.
  • Spring Framework 5.0 comes with its own Commons Logging bridge; spring-jcl instead of standard Commons Logging.
  • Support for providing spring components information through index file “META-INF/spring.components” rather than classpath scanning.
  • Spring WebFlux brings reactive programming to the Spring Framework.
  • Spring 5 also supports Kotlin programming now. This is a huge step towards supporting functional programming, just as Java is also moving towards functional programming.
  • Support for JUnit 5 and parallel testing execution in the Spring TestContext Framework.

48. What is Spring WebFlux?

Ans:

Spring WebFlux is the new module introduced in Spring 5. Spring WebFlux is the first step towards the reactive programming model in spring framework.
Spring WebFlux is the alternative to the Spring MVC module. Spring WebFlux is used to create a fully asynchronous and non-blocking application built on the event-loop execution model.

49. What are the benefits of using Spring Tool Suite?

Ans:

We can install plugins into Eclipse to get all the features of Spring Tool Suite. However, STS comes with Eclipse with some other important kinds of stuff such as Maven support, Templates for creating different types of Spring projects and tc server for better performance with Spring applications.
I like STS because it highlights the Spring components and if you are using AOP pointcuts and advice, then it clearly shows which methods will come under the specific pointcut. So rather than installing everything on our own, I prefer using STS when developing Spring-based applications.

50. Name some of the important Spring Modules?

Ans:

Some of the important Spring Framework modules are:

Spring Context – for dependency injection.

Spring AOP – for aspect oriented programming.

Spring DAO – for database operations using DAO pattern

Spring JDBC – for JDBC and DataSource support.

Spring ORM – for ORM tools support such as Hibernate

Spring Web Module – for creating web applications.

Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.

Course Curriculum

Enroll in Java Spring Course & Get Noticed By Top Hiring Companies

Weekday / Weekend BatchesSee Batch Details

51. What do you understand by Aspect Oriented Programming?

Ans:

Enterprise applications have some common cross-cutting concerns that are applicable to different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. 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 are not possible in normal object-oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data. Read more about Spring AOP support at Spring AOP Example.

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

Ans:

1. 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 a Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.

2. 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 Advices as Spring interceptors or Servlet Filters.

3. Pointcut: Pointcut are 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.

4. 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.

5. Advice Arguments: We can pass arguments in the advice methods. We can use 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 the argument type is determined.

These concepts seem confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to them.

53. What is the difference between Spring AOP and AspectJ AOP?

Ans:

AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:

Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.

Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.

Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ supports all kinds of pointcuts.

One of the shortcomings of Spring AOP is that it can be applied only to the beans created through Spring Context.

54. What is a Spring IoC Container?

Ans:

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;

  1. 1. AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
  2. 2. ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
  3. 3. FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
  4. 4. AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.

55. What is a Spring Bean?

Ans:

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.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.

56. What is the importance of Spring bean configuration files?

Ans:

We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean XML file and initializes all of them. Once the context is initialized, we can use it to get different bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.

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

Ans:

There are three different ways to configure Spring Bean.

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

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

2. Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes 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);

3. Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring beans. 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” />

58. What are different scopes of Spring Bean?

Ans:

singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.

prototype: A new instance will be created every time the bean is requested.

request: This is the same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.

session: A new bean will be created for each HTTP session by the container.

global-session: This is used to create global session beans for Portlet applications.

Spring Framework is extendable and we can create our own scopes too, however most of the time we are good with the scopes provided by the framework.
To set spring bean scopes we can use the “scope” attribute in bean element or @Scope annotation for annotation based configurations.

59. What is a Spring configuration file?

Ans:

Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

60. What is the default scope of bean in Spring framework?

Ans:

The default scope of bean is Singleton for Spring framework.

61. Are Singleton beans thread safe in Spring Framework?

Ans:

No, singleton beans are not thread-safe in Spring framework.

62. Can you inject null and empty string values in Spring?

Ans:

Yes.

63. How do you turn on annotation wiring?

Ans:

Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.

64. What does @Required annotation mean?

Ans:

This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.

65. What does @Autowired annotation mean?

Ans:

This annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.

66. What does @Qualifier annotation mean?

Ans:

There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

67.  Explain the Core Container (Application context) module

Ans:

This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container.

68. What is BeanFactory – BeanFactory implementation example

Ans:

A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.

The most commonly used BeanFactory implementation is the XmlBeanFactory class.

69. XMLBeanFactory

Ans:

The most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.

70. What components does a Spring application have?

Ans:

A typical Spring application can be subdivided into the following components:

  • 1. Bean Class – Contains properties, functions, setter and getter methods, et cetera
  • 2. Bean Configuration File – Contains information on classes as well as how to configure the same
  • 3. Interface – Defines the functions
  • 4. Spring Aspect Oriented Programming – Provides functionality of cross-cutting concerns
  • 5. User Program – Uses the function
Java Spring Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

71. How to create Spring Configuration File?

Ans:

Since Spring is based on the concept of Dependency Injection, all the classes, interfaces, and their dependencies are stored in a file termed as the spring configuration file. It is a .xml file. The spring container uses this file to control the lifecycle of spring beans. A bean is configured as:

  • <bean id = “…” class = “…” init-method = “…” lazy-init=”true” destroy-method=”….”>
  •  <!– bean dependencies and configurations –>
  • </bean>

72. Explain inner beans in Spring.

Ans:

Inner beans are the beans that exist within the scope of another bean. The concept is similar to inner classes in Java. The inner bean is defined as the target inside the outer bean id tag.

  • <bean id = “outerBean” class = “…”>
  •      <property name = “target”>
  •         <bean id = “innerBean” class = “…”/>
  •      </property>
  • </bean>

74. What classes does the JDBC API contain?

Ans:

  1. 1. JdbcTemplate
  2. 2. NamedParameterJdbcTemplate
  3. 3. SimpleJdbcCall
  4. 4. SimpleJdbcInsert
  5. 5. SimpleJdbcTemplate

75. How will you access Hibernate using Spring Framework?

Ans:

Hibernate can be accessed using Spring Framework in the following two ways:

  1. 1. Extending HibernateDAOSupport and then applying an AOP Interceptor node
  2. 2. Inversion of Control with a Hibernate Template and Callback

76. Could you draw a comparison between concern and crosscutting concerns in Spring AOP?

Ans:

While the concern is a behavior that the developer wants to have in a particular module of a Spring application, the cross-cutting concern is a concern that is applicable throughout the entire Spring application.

77.What do you understand by Spring MVC framework?

Ans:

The Spring MVC framework is responsible for providing model-view-controller architecture as well as ready-to-use components, used for developing flexible and loosely coupled web apps.

The MVC pattern helps in separating out the various aspects of the application, such as business logic, input logic, and UI logic, in addition to providing a loose coupling amongst these separated elements.

78. Please explain DispatcherServlet.

Ans:

The DispatcherServlet is the essence of Spring Web MVC framework and handles all the HTTP requests as well as responses. Upon receiving the entry of handler mapping from the configuration file, the DispatcherServlet forwards the request to the controller.

Thereafter, the controller returns an object of Model and View. Afterward, the Dispatcher Servlet checks the configuration file for the entry of view resolver and calls the specified view component.

79. Difference between FileSystemResource and ClassPathResource?

Ans:

In FileSystemResource you need to give path of spring-config.xml (Spring Configuration) file relative to your project or the absolute location of the file.

In ClassPathResource spring looks for the file using ClassPath so spring-config.xml should be included in classpath. If spring-config.xml is in “src” so we can give just its name because src is in the classpath path by default.

In one sentence, ClassPathResource looks in the class path and FileSystemResource looks in the file system.

80. Spring DAO support

Ans:

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows us to switch between the persistence technologies fairly easily and to code without worrying about catching exceptions that are specific to each technology.

81. ORM’s Spring support

Ans:

Spring supports the following ORM’s:

  • Hibernate
  • iBatis
  • JPA (Java Persistence API)
  • TopLink
  • JDO (Java Data Objects)
  • OJB

82. How can we integrate Spring and Hibernate using HibernateDaoSupport?

Ans:

Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps:

  1. 1. Configure the Hibernate SessionFactory
  2. 2. Extend a DAO Implementation fromHibernateDaoSupport
  3. 3. Wire in Transaction Support with AOP

83. Pointcut

Ans:

The pointcut is a set of one or more join points where an advice should be executed. You can specify pointcuts using expressions or patterns.

84. What is Introduction?

Ans:

An Introduction allows us to add new methods or attributes to existing classes.

85. What is a Target object?

Ans:

A target object is an object being advised by one or more aspects. It will always be a proxy object. It is also referred to as the advised object.

86. What is a Proxy?

Ans:

A proxy is an object that is created by applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

87. What are the different types of AutoProxying?

Ans:

  • BeanNameAutoProxyCreator
  • DefaultAdvisorAutoProxyCreator
  • Metadata autoproxying

88. What is Weaving? What are the different points where weaving can be applied?

Ans:

Weaving is the process of linking aspects with other application types or objects to create an advised object.

Weaving can be done at compile time, at load time, or at runtime.

89. Explain XML Schema-based aspect implementation?

Ans:

In this implementation case, aspects are implemented using regular classes along with XML based configuration.

What are the JSR-250 Annotations? Explain them.

Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.

  • @PostConstruct − This annotation can be used as an alternate of initialization callback.
  • @PreDestroy − This annotation can be used as an alternate of destruction callback.
  • @Resource − This annotation can be used on fields or setter methods. The @Resource annotation takes a ‘name’ attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.

90. How is event handling done in Spring?

Ans:

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.

91. Describe some of the standard Spring events.

Ans:

Spring provides the following standard events −

  1. 1. 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.
  2. 2. 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.
  3. 3. 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.
  4. 4. 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.
  5. 5. RequestHandledEvent − This is a web-specific event telling all beans that an HTTP request has been serviced.

92. What is bean wiring?

Ans:

Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them together.

93. What is bean auto wiring?

Ans:

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 a bean by inspecting the contents of the BeanFactorywithout using any elements.

94. Explain different modes of auto wiring?

Ans:

The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:

  • no: This is the default setting. Explicit bean reference should be used for wiring.
  • byName: When autowiring byName, the 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: When autowiring by data type, the 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’ names in the configuration file. If more than one such beans exist, a fatal exception is thrown.
  • constructor:This mode is 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 byType.

95. Are there limitations with autowiring?

Ans:

Limitations of autowiring are:

97. What is Spring Java-Based Configuration? Give some annotation examples.

Ans:

Java based configuration option enables you to write most of your Spring configuration without XML but with the help of a few Java-based annotations.

An example is a @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in the Spring application context.

98. What is the importance of the POM.XML file?

Ans:

Project Object Model (POM) is an XML formatted file in which all the configuration for a maven project is defined. The most commonly used tags in POM.XML are <groupid>, <artifactId>, <version>, <packaging> and a few more.

99. What does the @RequestParam annotation do?

Ans:

This allows the server side to read from data and automatically bind it to a parameter coming into the method.

100. What is Spring Security?

Ans:

Spring Security provides security services to J2EE applications. Spring Security is implemented using Servlet Filters under the hood. Servlet Filters are used to pre-process or post-process web requests.

Are you looking training with Right Jobs?

Contact Us

Popular Courses