1. What is Spring Framework?
Spring is an open-source framework created to address the complexity of building enterprise applications. It eases the development effort by providing IOC container, Dependency Injection, Aspect-oriented programming, etc. Spring framework also allows you to connect to other frameworks such as Struts, EJB, Hibernate, etc.
2. What are the advantages of Spring?
- Spring is a lightweight and easy to use framework, Spring IoC container automatically manages the spring bean life cycle, initialize the beans and inject them as dependencies.
- It enables us to create a loosely coupled application by Dependency Injection, where the framework creates the objects and supplies the required dependencies.
- Spring MVC is based on the MVC pattern, which allows you to create an MVC based web application.
- AOP enables cohesive development by separating the cross-cutting concerns from the business logic.
- Spring JDBC allows us to perform database operations without worrying about the boilerplate code such as the creation of a connection, transaction management, resource cleanup, etc.
- Spring Data JPA adds further abstraction of data access on JPA, we don’t need to worry about Data Access Layer or SQL queries.
3. What is Inversion of Control?
Inversion of Control or IoC is nothing but a Software Design Principle, independent of language, which does not create the objects but describes how object creation happens.
Inversion of Control is the principle, where the control flow of a program is inverted; instead of the programmer controlling the flow of a program, the framework takes control of the program flow.
4. What is Dependency Injection in Spring?
Dependency Injection is the pattern through which Inversion of Control achieved, through Dependency Injection, the responsibility of creating objects shifts from the application to the Spring IoC container. It reduces coupling between multiple objects as it is dynamically injected by the framework [Setter and Constructor injection].
5. Types of Dependency Injection supported by Spring?
Spring supports two types of Dependency Injection.
-
Setter Injection:
- Setter Injection is the simplest Dependency Injection, which injects the values via the setter method.
- Spring container uses setXXX() of the Spring bean class to assign a dependent variable to the bean property from the bean configuration file.
Example:
<bean id="employee" class="com.javainterviewpoint.Employee"> <property name="id" value="101"></property> <property name="name" value="Bob"></property> <property name="city" value="Chennai"></property> </bean>
-
Constructor Injection:
- Constructor Injection is the process of injecting the dependencies of an object through its constructor argument at the time of instantiation.
- Ioc Container can use one or more argument constructor to initiate the bean. We will be using <constructor-arg> tag, which is a subelement of the <bean> tag for Constructor Injection.
Example:
<bean id="employee" class="com.javainterviewpoint.Employee"> <constructor-arg value="111"/> <constructor-arg type="java.lang.String" value="Alice"/> <constructor-arg type="java.lang.String" value="Chennai"/> </bean>
6. Where to use Constructor Injection and Setter Injection?
As Constructor Injection does not allow partial injection, it is recommended to use a Constructor injection where all the parameters are mandatory.
On the other hand, Setter injection allows partial injection, and it can be used for optional dependencies.
7. How to Instantiate Spring IoC Container?
Spring provides us with two types of IoC Container implementation.
1. Bean Factory
2. Application Context
BeanFactory is the more basic implementation of Spring IoC Container, whereas the ApplicationContext is the more advanced implementation.
8. What is BeanFactory?
BeanFactory is an interface belonging to org.springframework.beans.factory.BeanFactory.
BeanFactory helps in implementing Inversion of Control in Spring. XMLBeanFactory is one of the most commonly used implementations.
9. What is ApplicationContext?
ApplicationContext is a subinterface of BeanFactory and represents the Spring IoC container and is responsible for Instantiating the bean, wiring the beans together, configuring the beans, and managing the bean’s entire life-cycle. ApplicationContext takes care of the bean life cycle and wiring up dependencies.
10. What is XMLBeanFactory?
XMLBeanFactory is the most commonly used BeanFactory implementation. It reads all the bean definitions mention in the XML configuration file and creates a fully configured application.
11. What are the common implementations of ApplicationContext?
ClassPathXmlApplicationContext – It loads the bean definitions mentioned in the XML file located in the ClassPath.
FileSystemXmlApplicationContext – It loads the bean definitions from the XML file present in the location passed.
XmlWebApplicationContext – It loads the bean definitions mentioned in the XML file which is present within the web application.
12. What are the responsibilities of an IoC container?
- Creating and Configuring the objects
- Managing the dependency between the objects.
- Wiring the objects together
- Managing the life cycle of the beans.
13. Difference between BeanFactory and ApplicationContext?
Both the BeanFactory and ApplicationContext are used to get beans from your spring IOC container, but still, there are some differences.
- BeanFactory instantiates bean when you call getBean() method while ApplicationContext instantiates bean when the container starts, It doesn’t wait for the call of getBean() method.
- BeanFactory allows you to read only one configuration file
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("SpringConfig.xml"));
Whereas ApplicationContext allows you to read one or more configuration files
ApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig.xml");
or
ApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig.xml", "SpringSecurityConfig.xml");
- BeanFactory is a basic container; it can create beans and inject dependencies to it, and will not provide support for other services like transaction management, security, messaging, etc. We have to use ApplicationContext in those places.
- BeanFactory does not support Internationalization (i18n), whereas ApplicationContext supports it.
- ApplicationContext has the ability to publish events to beans that are registered as a listener, which BeanFactory cannot.
- BeanFactory uses Lazy loading by default, whereas ApplicationContext uses Eager loading by default.
- ApplicationContext supports the autoscanning feature, whereas BeanFactory will not support it.
14. What are the different ways of providing configuration in Spring?
-
XML Based Configuration
The bean configurations will be mentioned in the XML File
<bean id="helloWorld" class="com.javainterviewpoint.HelloWorld"></bean>
-
Annotation Based Configuration
We can use the annotation such as @Component, @Controller, @Service, @Repository to mark a particular class as a bean and use @Autowired annotation to use the bean. This is was introduced in Spring 2.5
@Component public class HelloWorld { public void display(String message) { System.out.println(message); } }
This was introduced in Spring 3.0, where can specify the beans using @Bean annotation in Java class annotated with @Configuration annotation
package com.javainterviewpoint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HelloWorldConfig { @Bean(name="helloWorld") public HelloWorld getHelloWorld() { return new HelloWorld(); } }
15. Different beans scopes in Spring?
- singleton: This is the default scope of a bean, returns a single bean instance per Spring IoC container
- prototype: This scope returns a new bean instance each time for each request. It does not store any cache version like a singleton.
- request: This scope returns a single bean instance per HTTP request
- session: This scope returns a single bean instance per HTTP session
- application: This scope returns a single bean instance to the lifecycle of a ServletContext.
- websocket: This scope returns a single bean instance to the lifecycle of a WebSocket.
16. What is Static Factory Method?
The Static Factory Method allows you to get an instance of a bean through a static method.
package com.javainterviewpoint.springfactory;
public class StudentFactory
{
public static Student createStudent()
{
return new Student ();
}
}
Configuration:
<bean id="student" class="com.javainterviewpoint.springfactory.StudentFactory"
factory-method="createStudent">
</bean>
The factory-method attribute denotes the method that will be invoked while injecting the bean. It is used when the factory method is static
17. What is Instance Factory Method?
The Instance Factory Method allows you to get an instance of a bean through a non-static method.
package com.javainterviewpoint.springfactory;
public class StudentFactory
{
public Student getStudent()
{
return new Student ();
}
}
Configuration:
<bean id="student" factory-bean="student" factory-method="createStudent"> </bean>
factory-bean represents the reference of the bean by which the factory method will be invoked. It is used if the factory method is non-static. The class attribute is not required for Instance Factory Method.
18. How to define the scope of a bean?
We can add the scope attribute if we are using XML based configuration like below
<bean id="employee" class="com.javainterviewpoint.Employee" scope="prototype"/>
If we are using annotation-based bean configuration, then we can use the @Scope annotation to define the scope of a bean
@Configuration
public class ApplicationConfig {
@Bean("employee")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Employee getEmployee() {
return new Employee();
}
}
19. Is singleton bean thread-safe in Spring?
No, Spring doesn’t guarantee thread-safety of a singleton bean. Spring creates a Singleton bean, but if it is mutable then it might not be thread-safe. It is the responsibility of the developer’s responsibility to ensure thread-safety.
20. What are the init-method and destroy-method attribute?
By setting the init-method and destroy-method attribute in the configuration file. we can have our own custom method acting as initializing and destroy methods.
The init-method gets called during the bean creation, it is useful for loading the pre-configuration needed for the bean, and the destroy-method gets called when the ApplicationContext gets destroyed.
<bean id="initdest" class="com.javainterviewpoint.HelloWorld" init-method="initMethod" destroy-method="destroyMethod"/>
21. What are inner beans in Spring?
Inner beans are the beans that are defined in the scope of another bean. The inner bean can be defined within a </property> tag or </constructor-arg> tag
<bean id="classroom" class="com.javainterviewpoint.ClassRoom"> <property name="student"> <bean class="com.javainterviewpoint.Student"/> </property> </bean>
We don’t have to use a ref attribute in the property tag.
We can define inner beans in a constructor-arg tag like below
<bean id="classroom" class="com.javainterviewpoint.ClassRoom"> <constructor-arg> <bean class="com.javainterviewpoint.Student"/> <constructor-arg> </bean>
22. What is Autowiring in Spring?
Autowiring is a feature of the Spring framework which lets you to Inject Dependency implicitly, Spring container automatically wires the corresponding bean by reading the configuration file. We just need to add the autowire attribute in the configuration.
23. What are the different types of Autowiring in Spring?
-
Autowiring byName:
This type of autowiring injects the bean based on the name, with that being said the bean id and the property name have to be the same.
public class Bean1 { public Bean2 b2; public Bean2 getB2() { return b2; } public void setB2(Bean2 b2) { this.b2 = b2; } } public class Bean2 { } <bean id="b1" class="com.javainterviewpoint.Bean1" autowire="byName"></bean> <bean id="b2" class="com.javainterviewpoint.Bean2"></bean>
-
Autowiring byType:
In this type of autowiring, the property name and bean id need not be the same. Property’s class type is used for searching a matching bean definition in the configuration file.
public class Bean1
{
public Bean2 b2;
public Bean2 getB2() {
return b2;
}
public void setB2(Bean2 b2) {
this.b2 = b2;
}
}
public class Bean2
{
}
<bean id="b1" class="com.javainterviewpoint.Bean1" autowire="byType"></bean> <bean id="b2" class="com.javainterviewpoint.Bean2"></bean>
-
Autowiring constructor:
This is similar to autowiring byType, but applies to constructor arguments. This type of autowiring looks for the class type of constructor arguments.
public class Bean1
{
public Bean2 b2
public Bean1(Bean2 b2)
{
this.b2 = b2;
}
}
public class Bean2
{
}
<bean id="b1" class="com.javainterviewpoint.Bean1" autowire="constructor"></bean> <bean id="b2" class="com.javainterviewpoint.Bean2"></bean>
- Autowiring autodetect [Deprecated]: The autodetect will first try to autowire by the constructor if it doesn’t work then it tires to autowire byType. This autowiring is deprecated from Spring 3.
- no Autowiring – This means no autowiring, the bean must be injected using the ref tag.
<bean id="b1" class="com.javainterviewpoint.Bean1">
<property name="b2" ref="b2"/>
</bean>
<bean id="b2" class="com.javainterviewpoint.Bean2"></bean>
- Autowiring with @Autowired annotation: we can use @Autowired annotation on variables, methods, and constructors.
24. Does autowiring work for primitive datatypes?
No, Autowiring cannot be used to inject primitive such int, boolean, double, etc.. It works with reference only, alternatively we can use wrapper for the same. i.e. Integer, Boolean, Double, etc.
25. How to exclude a Bean from Autowiring?
We can exclude a bean from autowiring, by setting the autowire-candidate attribute to “false”.
<bean autowire-candidate="false" id="bean1" class="com.javainterviewpoint.Bean1"/>
26. How to lazy initialize Spring beans?
We know BeanFactory by default lazy loads all the bean, whereas the ApplicationContext uses eager load. By setting the lazy-init attribute to “true”, we can enable lazy loading of beans.
<bean lazy-init="true" id="bean1" class="com.javainterviewpoint.Bean1"></bean> <bean lazy-init="true" id="bean2" class="com.javainterviewpoint.Bean2"></bean>
27. Optional Dependency Injection using Spring? or How to avoid NoSuchBeanDefinitionException?
The NoSuchBeanDefinitionException occurs when Spring is not able to resolve the dependency. By default @Autowired annotation needs to resolve all its dependencies, if not we will get the exception.
However, we can override the behavior by setting required to “false”, this will enable optional dependency injection.
public class Bean1 { @Autowired (required = false) public Bean2 b2; } public class Bean2 { }
In the above code, the container will try to autowire Bean2, if it is not able to resolve the dependency, it will not throw NoSuchBeanDefinitionException.
28. What are @PostConstruct and @PreDestroy annotations?
@PostConstruct and @PreDestroy are annotation equivalent of int-method and destroy-method attributes respectively in the XML configuration.
We can annotate the method that performs the initialization tasks with @PostConstruct annotation and the method performs the cleanup activity with @PreDestroy.
29. How to resolve Constructor injection ambiguity?
Suppose if we have multiple constructs in a bean.
package com.javainterviewpoint; public class Student { private String name; private int age; public Student(String name, String age) { super(); System.out.println("Inside Constructor 1"); this.name = name; this.age = Integer.parseInt(age); } public Student(String name, int age) { super(); System.out.println("Inside Constructor 2"); this.name = name; this.age = age; } }
Now, we try to inject the values
<bean id="student" class="com.javainterviewpoint.Student"> <constructor-arg value="Bob" /> <constructor-arg value="85" /> </bean>
Instead of getting into Constructor 2, values will get injected through Constructor 1. This happens as there is ambiguity in the parameter types.
This can be resolved by explicitly specifying the type attribute in the <constructor-args>
<bean id="student" class="com.javainterviewpoint.Student"> <constructor-arg type="java.lang.String" value="Bob" /> <constructor-arg type="int" value="85" /> </bean>
Now the values will be injected through the correct constructor (constructor2)
30. Use of @Configuration annotation?
The @Configuration annotation on a class indicates the container that this class is a source of bean definitions. The beans can be defined using the @Bean annotation. We are allowed to have more that one @Configuration annotated classes.
31. How to avoid NoUniqueBeanDefinitionException?
The NoUniqueBeanDefinitionException exception occurs while autowiring, the container detected more than one bean of the same type.
We can use the @Qualifier annotation and specify the bean name which has to be resolved by the container.
32. What is a PropertyPlaceholderConfigurer?
The PropertyPlaceholderConfigurer allows you to externalize the property file and read it through Spring.
For example, rather than hardcoding the JDBC Connection details in SpringConfig.xml, we can externalize them into a property file and read it through the PropertyPlaceholderConfigurer.
jdbc.properties
jdbc.url = jdbc:oracle:thin:@rsh2:41232:mydb1 jdbc.username = root jdbc.password = test
SpringConfig.xml
<bean id="jdbcproperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <bean id="jdbc" class="com.javainterviewpoint.HelloWord"> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean>
33. What is the function of <context:annotation-config> ?
<context:annotation-config> is used to activate annotations in beans already registered in the application context. Enables us to use annotations that are restricted to wiring up properties and constructors such as @Autowired, @Required, etc.
34. Use of @Requred annotation
The Spring dependency checking feature can check only for all properties is set or not, we cannot validate only for certain fields. In those cases, we can use @Required annotation on the setter method.
The @Required annotation is method-level annotation, indicates that a value must be injected for the particular property.
35. What is the use of @Primary annotation?
@Primary annotation indicates that this bean should be given higher precedence when there are multiple beans of the same type is available. The @Primary annotation should be used in conjunction with @Bean or @Autowired annotation
@Configuration public class ApplicationConfig { @Bean @Primary public Employee getManager() { return new Manager(); } @Bean public Employee getWorker() { return new Worker(); } }
The getManager() will be given higher preference.
36. What is Spring MVC Framework?
The Spring MVC follows Model-View-Controller (MVC) architecture, which allows us to create a loosely coupled web application. Spring MVC revolves around the DispatcherServlet, which preforms crucial operations such as dispatching the requests to handlers, configuring handler mappings, locale, view resolution, etc.
- Model – The Model is nothing but a simple POJO, consist of the application data.
- View – The View is responsible for rendering the HTML output which the client’s browser can interpret.
- Controller – The Controller is responsible for calling the appropriate service for processing the data and pass the processed data to view component.
37. Explain Spring MVC Flow?
- The DispatcherServlet receives the first request.
- Now the DispatcherServlet checks the HandlerMapping and the calls the appropriate Controller.
- The Controller calls the service class and returns the ModelAndView object back to the DispatcherServlet.
- The DispatcherServlet calls the ViewResolver by passing the view name, to get the actual view to invoke.
- Finally, the DispatcherServlet passes the Model to the View to render the output to the user.
38. What are the different types of HandlerMappings available?
There are three different handler mappings available in Spring
SimpleUrlHandlerMapping allows us to specify URL pattern and handler explicitly
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <value> /welcome.htm=WelcomeController /welcome*=WelcomeController /hello*=HelloController /helloWorld.htm=HelloController </value> </property> </bean>
In BeanNameUrlHandlerMapping we will map each request to a Bean directly. The DispatcherServlet by default uses BeanNameUrlHandlerMapping
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <bean name="/helloWorld.htm" class="com.javainterviewpoint.HelloController" /> <bean name="/hello*.htm" class="com.javainterviewpoint.HelloController" />
ControllerClassNameHandlerMapping uses a convention to map the requested URL to the Controller. It will take the Controller name and converts them to lower case with a leading “/”
<bean class="org.springframework.web.servlet.mvc.support. ControllerClassNameHandlerMapping" /> <bean class="com.javainterviewpoint.HelloWorldController"></bean> <bean class="com.javainterviewpoint.WelcomeController"></bean>
39. Difference between <context:annotation-config> vs <context:component-scan>?
<context:annotation-config> tag activates the annotation of the beans which is already registered in the application context. It activates annotations like @Autowired, @Qualifier, @Inject, @PostConstruct, @PreDestroy, @Resource, etc.
<context:component-scan> tag registers the beans to the context and also scans the annotations in the beans and activate them.
<context:component-scan> is nothing but <context:annotation-config> + Bean Registration.
40. What is ContextLoaderListener?
The ContextLoaderListener reads the Spring configuration file and initializes all the singleton beans defined in this file. It looks for beans specified in contextConfigLocation in web.xml.
<servlet> <servlet-name>Spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/beans.xml</param-value> <param-value>/WEB-INF/data.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
41. What is the use of @RequestParam annotation?
@RequestParam annotation is used to get the request parameters from URI, also known as query parameters.
If we have an incoming request with order id – http://shopping.com/orders?orderId=123
Then we can read the get the orderId, using @RequestParam like below
@RequestMapping("/orders") public String getOrderDetails(@RequestParam("orderId") String orderId) { return "orderDetails"; }
42. What is the use of @PathVariable annotation?
@PathVariable annotation is used to extract values from URI.
Request URI – http://javainterviewpoint.com/users/111
We can get the userId by using @PathVariable like below
@RequestMapping("/users/{userId}") public String getUserDetails(@PathVariable String userId) { return "userDetails"; }
43. What is a Controller in Spring MVC?
The Controller class can handle one or more requests, it calls the appropriate service class to perform the business logic and returns the ModelAndView object to the DispatcherServlet.
We can create a simple controller class by annotating it with the @Controller stereotype annotation. It matches the path of the incoming request with the @RequestMapping annotated methods.
44. What is a ModelAndView in Spring MVC?
The ModelAndView is just a container for holding both Model map and View objects, It enables the Controller to return them as a single entity.
ModelAndView modelAndView = new ModelAndView("showStudentDetails"); modelAndView.addObject("student", new Student(1,"Bob")); return modelAndView;
In the above snippet, “showStudentDetails” is the View name and the “Student” is the Model object.
45. What is the difference between @Controller and @RestController?
@Controller returns the view name which will be resolved by the ViewResolver and rendered to the user.
@RestController directly returns the bean object which will be converted into a JSON or XML format.
In simple we can say @RestController = @Controller + @ResponseBody
46. What is the default scope of a Controller?
By default, the scope of the Controller will be a singleton, the objects will be shared across all requests and sessions. We can also change the scope using @Scope annotation.
47. What is a Spring Interceptor?
Spring Interceptors are like Servlet Filters, it allows you to intercept each request and process them. All the interceptors must implement the HandlerInterceptor interface or extend the HandlerInterceptorAdapter class.
- preHandle(): The preHandle() method runs before the actual handler execution.
- postHandle(): The postHandle() method runs after the handler execution but before the view render.
- afterCompletion(): The afterCompletion() method runs after the request completion and the view is render.
48. What is the use of @ExceptionHandler annotation?
@ExceptionHandler works at the Controller level and it is only active for that particular Controller, not globally for the entire application.
@Controller public class StudentController { ....... @ExceptionHandler(IOException.class) public ModelAndView processIOException(IOException ioe) { ModelAndView modelAndView = new ModelAndView("exception"); modelAndView.addObject("name", ioe.getClass().getSimpleName()); modelAndView.addObject("message", ioe.getMessage()); return modelAndView; } }
In the above code, we have used the @ExceptionHandler to catch the IOException, this block works only within the StudentController and not in any other Controller
49. What is the use of @ControllerAdvice annotation?
@ControllerAdvice is used for global error handling in the Spring MVC application. It works across all the Controllers.
@ControllerAdvice public class GlobalExceptionHandler { ....... @ExceptionHandler(IOException.class) public ModelAndView processIOException(IOException ioe) { ModelAndView modelAndView = new ModelAndView("exception"); modelAndView.addObject("name", ioe.getClass().getSimpleName()); modelAndView.addObject("message", ioe.getMessage()); return modelAndView; } }
The above code catches IOException across all the Controllers.
50. How to avoid web.xml in a Spring MVC application?
From Spring 3.0, we can configure the container with zero XML. Spring provides us with AbstractAnnotationConfigDispatcherServletInitializer class which allows us to register ContextLoaderlistener and DispatcherServlet like the typical web.xml.
public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class<?>[] getRootConfigClasses() { return new Class[] {RootConfiguration.class}; } protected Class<?>[] getServletConfigClasses() { return new Class[] {WebMvcConfiguration.class}; } protected String[] getServletMappings() { return new String[] {"/"}; } }
51. What is the use of @EnableWebMvc annotation?
@EnableWebMvc annotation allows us to enable Spring MVC through Java configuration if we are not using the traditional XML Spring configuration file. @EnableWebMvc is simply equal to <mvc:annotation-driven />
52. How to perform Spring Bean validation?
We just need to add a @Valid annotation before @ModelAttribute [receives the values of the submitted form]. This validates the Model object received and stores the result in the BindingResult object.
@RequestMapping(value="/register",method=RequestMethod.POST) public String processRegistration(@Valid @ModelAttribute("sb") StudentBean sb, BindingResult result) { if(result.hasErrors()) { System.out.println(result); return "registrationForm"; } ....... }
On the StudentBean we should have enabled the validation annotations like below, @NotEmpty, @Size etc..
package com.javainterviewpoint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; public class StudentBean { @NotEmpty(message="FirstName cannot be empty") @Size(min=1,max=6,message="Size should be between 1 to 6") String firstName; @NotNull @Size(min=1,max=6,message="Size should be between 1 to 6") String lastName; @NotEmpty(message="Atleast one hobby has to be selected") String[] hobby; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } }
53. What is the use of the @ModelAttribute in Spring MVC?
The ModelAttrubute gets all the values from the submitted form and automatically assigns it to the bean object.
Suppose if we have a form like below
<form:form action="register" modelAttribute="sb">
First Name : <form:input path="firstName" />
<br><br>
Last Name : <form:input path="lastName" />
<br><br>
<input type="submit" value="submit"/>
</form:form>
And at Controller we have
@RequestMapping(value="/register",method=RequestMethod.POST)
public String processRegistration(@Valid @ModelAttribute("sb") StudentBean sb, BindingResult result)
{
if(result.hasErrors())
{
System.out.println(result);
return "registrationForm";
}
.......
}
The submitted form values will be automatically assigned to the sb (StudentBean) object through ModelAttribute. The point to remember here is the value of both ModelAttribute (form & controller) has to be the same.
54. What is the use of the BindingResult in Spring MVC?
The BindingResult holds the result of the validation and the errors have occurred during validation. Whenever Spring finds the @Valid annotation it validates the bean passed with the available validators and automatically registers the errors in the BindingResult.
55. How to configure a ViewResolver?
The ViewResolver enables the DispatcherServlet to render the correct view after processing the request. The most commonly used ViewResolver is InternalResourceViewResolver, we can configure it like below
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
The prefix is nothing but the folder to look for the view files and suffix is the type of file.
56. What is Aspect-Oriented Programming (AOP)?
Aspect-Oriented Programming or AOP is a pattern that enables us to modularize crosscutting concerns such as Transaction management, auditing, logging, etc.. which can be separated out from the business logic.
57. What is an Aspect?
An Aspect is the actual crosscutting concern that needs to be implemented such as logging, transaction management, etc.. An Aspect can be implemented by using @Aspect annotation.
Aspect = Advice + PointCut
58. What is Advice?
Advice defines the action taken by the Aspect at that point, in simple terms, we can say Advice is the implementation of Aspect, as it defines what action has to take place and when.
59. What are the Types of Advice?
- Before – This Advice runs before the advised method is invoked, It is denoted by @Before annotation.
- After – This Advice runs after the advised method completes its execution, the outcome is not considered either successful completion or exception occurred, It is denoted by @After annotation.
- AfterReturning – This Advice runs after the advised method completes its execution successfully without any exception, It is denoted by @AfterReturning annotation.
- AfterThrowing – This Advice runs after the advised method throws an exception, It is denoted by @AfterThrowing annotation.
- Around – This Advice wraps around the advised method and runs before and after the execution of the advised method. It is denoted by @Around annotation.
60. What is a JoinPoint?
JoinPoint is nothing but the point where we can apply the Advice. For example, Advice can be applied for each method call, or when an exception is thrown or when a variable is modified etc..
61. What is PointCut?
A PointCut is a combination of JoinPoints, and it specifies that at which JoinPoint the Advice will be executed. We can specify the PointCut by explicitly specifying the class name or through regular expression.
62. What is Weaving?
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. Spring AOP does weaving at runtime.
63. What is a JdbcTemplate?
JdbcTemplate is the core of Spring JDBC, it allows us to perform all database operations with ease, as it handles all the boilerplate code involved in Creating connection, Statement, closing the Resultset and Connection, Exception handling, Transaction management, etc.
The JdbcTemplate class instances are thread-safe, we can use JdbcTemplate to perform all the DML operations such as insert, select, update, and delete.
64. How to configure Spring JdbcTemplate?
We just need to configure the data source and pass the data source bean reference to the JdbcTemplate bean.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@local:14311:dev" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
65. How to enable Transaction management in Spring?
We just need to add to @Transactional annotation on the class, the default transaction level will be REQUIRED.
66. What are the different Propagation supported in Spring?
- REQUIRED
- REQUIRES_NEW
- NESTED
- MANDATORY
- NEVER
- NOT_SUPPORTED
- SUPPORTS
67. What are the different isolation levels supported by Spring?
- DEFAULT
- READ_COMMITTED
- READ_UNCOMMITTED
- REPEATABLE_READ
- SERIALIZABLE
68. What are the different ORM supported by Spring?
- Hibernate
- JPA
- JDO
- TopLink
- iBATIS
69. What is Spring Data JPA
With Spring Data JPA we don’t have to write the DAO layer or SQL statements, we just need to extend the Spring Data JPA repositories such as CrudRepository, PagingAndSortingRepository, JpaRepository, etc and create the Entity object to enable relational mapping. Spring provides the proxy implementation for the interfaces.
70. What is the JPQL?
JPQL is the Java Persistence Query Language defined in JPA specification.
71. Difference between JPA and Spring Data JPA?
JPA is just a specification, it specifies how a Java object has to be mapped to a relational database. There are several JPA providers, like Hibernate, EclipseLink, or Open JPA
Spring Data JPA adds further data access abstraction on JPA. Just like JPA, Spring Data JPA cannot work without a JPA provider. Spring Data JPA can also work with Hibernate, Eclipse Link, or other JPA providers.
72. What is the difference between Hibernate and Spring Data JPA?
Hibernate is a JPA implementation, whereas Spring Data JPA adds additional data access abstraction on JPA. Spring Data JPA cannot work without a JPA provider.
73. What is the difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?
- The CrudRepository extends the Repository interface, whereas the JpaRepository extends the PagingAndSortingRepository which inturn extends CrudRepository.
- The CrudRepository provides the support for the basic CRUD operations [Create, Read, Update, Delete], on the other hand, JpaRespository along with CRUD operations, it provides support for additional JPA related functionalities like flush context, delete in batch, etc.
74. What is NamedParameterJdbcTemplate?
NamedParameterJdbcTemplate allows us to assign names to the parameter placeholders and pass in a map so the template can match the map names to the placeholders.
String query = "insert into Employee (id, name, department) values (:id, :name, :department)"; Map<String, String> params = new HashMap<>(); params.put("id", "101"); params.put("name", "Bob"); params.put("department", "Blog"); namedParameterJdbcTemplate.update(query, params);
75. How to rollback a Spring Transaction?
By default all the methods marked with @Transactional annotation, rollback automatically happens whenever a RuntimeException occurs.
However rollback will not automatically happen for Checked Exception, but we can configure it by adding the rollbackFor attribute in the @Transactional annotation
@Transactional(rollbackFor=Exception.class)
76. Limitations of @Transactional annotation?
- Only public methods must be annotated with @Transactional annotation, though it will not raise an error if the method is not public but the transactional behavior will not work.
- The call must be made from outside the bean, as the transactional behavior is based on proxies if we call a transactional method from another method within the same class, will not enable the transactional behavior.
77. What is the use of @Entity annotation?
@Entity annotation defines that a class can be mapped to a table through an ORM.
78. What is @GeneratedValue annotation?
@GeneratedValue annotation specifies how the primary key should be generated, it configures the way to increment the specified column.
79. What are the different generated strategies supported?
- GenerationType.TABLE
- GenerationType.SEQUENCE
- GenerationType.IDENTITY
- GenerationType.AUTO
80. How to persist an entity object through EntityManager?
- Create the EntityManagerFactory
- Get the EntityManager through the EntityManagerFactory
- Initialize the EntityManager and persist the employee object in the database.
- Commit the transaction and close the resources.
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Emplyoee"); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(employee); entityManager.getTransaction().commit(); entityManager.close(); entityManagerFactory.close();
Hope this Spring Interview Questions and Answers will help you in the interview, do let me know if any question needs to be added.
Happy Job Search!! 🙂
Leave a Reply