This Web Developer Interview Questions post is about MVC Interview Questions for Java Spring that will explore various features, concepts and FAQs regarding Java Spring Framework. It’s basically a thorough collection of most frequently asked Spring MVC Interview Questions for Java developers. We already have covered another comprehensive list of Interview Questions related to Microsoft ASP.NET MVC that you can follow here.
You can find latest Java Developer Jobs at the end of this Java Spring MVC tutorial.
Java Spring MVC Interview Questions List
- What is Java Spring MVC Framework?
- What are the benefits of using Spring Framework?
- What are the Modules in Spring Framework? Kindly explain the key modules in Spring in detail including Core, Bean, Context, Expression Language, JDBC, ORM, OXM, JMS etc.
- What is Dependency Injection? What are the different Types of IoC Dependency Injection? What are the benefits of using DI? How to implement DI in Spring Framework?
- What is Spring IoC Container? What are different types of IoC Container? Explain each with the help of an implementation example. What are the key differences between various types of IoC Containers?
- What are Spring beans? How do we add a bean in spring application?
- How to define a bean scope?
- What are inner beans in Java Spring Framework
- Explain in detail about Bean life cycle in Spring framework with the help of a diagram?
- What is Bean Factory? How to use XMLBeanFactory? Explain with the help of a practical example?
- What are the differences between Singleton and Prototype Bean? Give an example of using both?
- What is AOP (Aspect Oriented Programming)? Explain in detail with the help of an example? Explain more related concepts including Aspect, Advice, JointPoint, PointCut and Advice Argument etc.
- How to setup LDAP authentication using Spring Framework? Explain all steps with proper diagram.
What is Java Spring MVC Framework?
Spring MVC is a solution to use the concept of MVC in Spring Framework. In Spring MVC, it is done with the help of DispatcherServlets. Before going some in depth of spring mvc, lets have a quick look on what MVC is.
MVC, is a shorthand of Model View Controller, which separates the different areas of our application and provides loose coupling. While Model have the application data, view is responsible for rendering the model data and display on HTML page. Controller’s responsibility is to process user requests, building the appropriate model and redirect to a particular view to display.
Spring MVC Framework uses dispatcher servlet for handling HTTP Request and provides HTTP Response. Lets have a look using diagram how Dispatcher servlets handles request and provides response and some components that are being used by dispatcher servlet.
The above diagram illustrates the events for an HTTP request to DispatcherServlet. Below is the brief description about the events :
- Once DispatcherServlet receives the HTTP request, first thing it does is to go to HandlerMapping to call the controller corresponding to the request.
- Once control comes to Controller, it takes the request and call the methods and executes the business logic and sets the data in model. Once it does all these it returns the view name to DispatcherServlet.
- Taking help from the view resolver, Dispatcher servlet picks the view for the request.
- Once dispatcher servlet gets the view, it passes the model data to view and the same view has been displayed on browser.
What are the benefits of using Spring Framework?
Followings are the key benefits of using Java Spring MVC Framework:
- Spring uses POJO model that is easy for development.
- Dependency Injection design pattern is used in spring which provides loose coupling.
- It uses Light weight IoC containers that are lightweight when compared with EJB containers.
- Spring provides transaction management, which is very useful.
- Spring code is more modular and more readable.
- Spring web framework uses MVC which is an advantage when compared to other Web Frameworks.
What are the Modules in Spring Framework? Kindly explain the key modules in Spring in detail including Core, Bean, Context, Expression Language, JDBC, ORM, OXM, JMS etc.
Spring, a potential candidate for all enterprise applications. It provides a number of modules to pick according to need. We will discuss all the modules one by one. But going forward lets take an simple diagram that illustrates all the modules. We will subdivide some modules to a submodule that these corresponds to:
Lets dig into each module one by one:
WEB Module:
Web layer provides support to create web related stuff using portlet, servlet, web-socket. Here Spring MVC comes into picture. Where portlet module provides mvc implementation to be used in portlet, web module provides basic web integration features, web-mvc module contains mvc and rest webservices for web applications.
DataAccess Module:
Data Access layer consists of different modules as ORM, OXM, JMX, JMS, JDBC.
Jdbc module provides a abstract layer that enables user to get rid of Jdbc coding. Transaction modules supports transaction management(Declarative transaction) for the classes that implements the specific interfaces. ORM provides integration layer for ORM api’s including ORM frameworks like Hibernate, JPA. OXM provides a layer that supports Object/XML mapping such as JAXB, XML Beans etc. JMS module implements features for consuming and producing messages.
Core Module:
Core module layer consists of bean, expressionLanguage, core and context. Where Bean module provides BeanFactory which is implementation of factory pattern, core provides features like IoC and dependency injection, context module provides support for internationalization, resource loading, it also supports EJB, JMX etc. ExpressionLanguage provides support to method invocation, accessing collections and indexers, named variables, logical andarithmeticic operators.
AOP, Instrumentation, Aspects and Messaging:
AOP module provides aspect oriented programming capability that enables user to write clean code using interceptors that decouple the code and functionality that can be seprated, Aspects module provides integration with AspectJ, yet another powerful aspect of aspect oriented programming, Instrumentation module provides class loader implementation to be used in certain application servers, Messaging module provides foundation for messaging based applications.
Testing
Testing module provides support for spring application to test with testing frameworks like TestNG and JUnit.
What is Dependency Injection? What are the different Types of IoC Dependency Injection? What are the benefits of using DI? How to implement DI in Spring Framework?
Dependency Injection related can be considered to be the most important question in list of Spring MVC Interview Questions. Dependency is something what we can say an object that can be used in other service that needs it, without having much knowledge about it and constructed object will be passed to service by some external entity. Now a service that needs this object either can create an object or what can be done is, a readymade object is passed to the service. Now in earlier version what we are doing is we are creating a hard dependency between object and service that is creating the object. To get rid of this what can be done is, a readymade object is passed to the service and it will be used wherever is required. This is dependency injection, where object is passed to service by external entity and service is not responsible for creating object.
Lets take a simple example:
Lets say we have a service that regularly checks for data modification in database and this service uses a class called ModificaitonPoller that regularly polls the modification of data.
Now lets simulate this using a traditional approach:
1 2 3 4 5 6 7 8 9 10 11 |
public class DataModificationService { private ModificationPoller poller; public DataModificationService(){ poller = new ModificationPoller(); } //service stuff goes here } |
In this example what we have created is we have created a dependency between DataModificationService and ModificationPoller.
Lets try to achieve using DI (Dependency Injection) approach:
1 2 3 4 5 6 7 8 9 10 11 |
public class DataModificationService { private ModificationPoller poller; public DataModificationService(ModificationPoller poller){ this.Poller = poller; } //service stuff goes here } |
Here ModificationPoller is implemented/created somewhere else and passed as dependency in DataModificaitonService at the time of object construction. This is a simple example of Dependency Injection.
DependencyInjection uses Inversion Of Control(IoC) to resolve dependencies, wherein a client delegates the responsibility of providing dependencies to external entity. Service/Client doesn’t need to know about how to construct the dependencies, these will be provided by some external entity. This separates the responsibilities of use and construction.
Types of InversionOfControl DependencyInjection :
There are three type of IoC DependencyInjection:
- Inject using Constructer
- Inject using setters
- Inject using Interface
Lets take examples of each:
Inject using Constructor
This is same as that we talked earlier, dependency is passed in constructer.
1 2 3 4 5 6 7 8 9 10 11 |
public class DataModificationService { private ModificationPoller poller; public DataModificationService(ModificationPoller poller){ this.Poller = poller; } //service stuff goes here } |
Inject using setters
In this method dependency is injected using setter method. Below is the example for the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class DataModificationService { private ModificationPoller poller; public DataModificationService(){ // } public void setModificationPoller(ModificationPoller poller){ this.poller = poller; } //service stuff goes here } |
Inject using Interface
In this approach there will a interface that will provide a setter method for injecting deprendency. Below is the example for the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public interface IModificationPollerSetter { public void setModificaitonPoller(ModificaitonPoller poller); } public class DataModificationService implements IModificationPollerSetter { private ModificationPoller poller; @Override public void setModificaitonPoller(ModificaitonPoller poller) { this.poller = poller; } } |
Benefits of DI :
- Dependency injection looses coupling between class and its dependency.
- Using DI, one more important principle that is ‘OpenClosePrinciple’ is satisfied, since the service/client is open for extension and close for modification.
- A lot of boilerplate code is removed from client/service.
- Ease is testing, using DI testing becomes easy to test, since dependencies can be easily mocked and inject in test.
- Code becomes more reusable since dependency can be configured differently for other objects.
- DI allows service/client to be independent and don’t need to have all knowledge of concrete implementation. It helps service to isolate from the design changes if there are any.
Dependency Injection and Spring:
Spring provides two ways to inject dependencies
- Inject dependency using constructor
- Inject dependency using setter
- Inject dependency using annotations
We already covered the concept, lets take example how it can be achieved in spring.
Inject dependency using constructor
To achieve this <constructor-arg> tag will be used. Config file will declare the bean and set the dependency. Lets see how config will look like:
1 2 3 4 5 |
<bean id="DataModificationService" class="com.springmvc.docs. DataModificationService"> <constructor-arg> <bean class="com.springmvc.docs.ModificationPoller" /> </constructor-arg> </bean> |
Here we injected the ModificationPoller into DataModificationService.
Java code will moreover look the same as we discussed earlier in inject using constructor.
Inject dependency using Setter
To achieve this, config file will have to declare the bean and inject using the <property> tag. Lets see how config will look like:
1 2 3 4 5 |
<bean id="DataModificationService" class="com.springmvc.docs. DataModificationService"> <property name="poller" ref="Poller"></property> </bean> <bean id="Poller" class="com.springmvc.docs.ModificationPoller" /> |
Here we injected the ModificationPoller into DataModificationService using setter approach.
What is Spring IoC Container? What are different types of IoC Container? Explain each with the help of an implementation example. What are the key differences between various types of IoC Containers?
Before digging more into it, lets talk about IoC. What IoC is? IoC , Inversion of Control is a principle that is driven by DI (Dependency Injection). Dependency Injection is design principle about object construction, how object will be created and how the dependencies will be defined, there are multiple ways to achive this, like injecting dependencies in object constructor or using setter methods or using annotations. Now here container comes into picture, how these dependencies will be injected. The container injects the dependencies when creating bean.
IoC container is responsible for creating, configuring and assembling bean and its dependencies. Xml’s are defined , from where container gets the information about creating bean and what all dependencies needs to be injected while creating this bean.
There are two types of IoC containers
- Application Context
- Bean Factory
Application Context
Defined by org.springframework.context.ApplicationContext interface, ApplicationContext is a advanced spring container. ApplicationContext comes with some very handy features like Generic way to load resources, messagesource access, BeanPostProcessor registration etc.
There are several ApplicationContext implementations, mostly used implementations are listed below:
- FileSystemXmlApplicationContext
- ClassPathXmlApplicaitonContext
- XmlWebApplicationContext
Lets discuss one by one with example in which based on file extension, some processing needs to be done. In the example we will not discuss the processing part but surely will demonstrate how the value is been loaded from xml file and how it is been loaded from application context.
FileSystemXmlApplicationContext: As the name suggests it loads the xml config file from file system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class FileExt{ private String fileExtension; public FileExt(){ //NoOp } public String getFileExtension() { return fileExtension; } public void setFileExtension(String fileExtension) { this.fileExtension = fileExtension; } } |
In the example above a class is created named FileExt and the file extension will be set from config file.
1 2 3 |
<bean id="FileExtBean" class="FileExt"> <property name="fileExtension" value="json"/> </bean> |
And when we code the main class that will load the config file, main class would look like, lets assume the directory in which my config file “c:\\springmvc\\docs”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("C:\\springmvc\\docs\\beans.xml"); FileExt fileExtension = (FileExt)context.getBean("FileExtBean"); //Code goes here to handle according to file extension } } |
ClassPathXmlApplicaitonContext: As the name suggests, it loads the xml file available in classpath. Lets take an example how code will look like. Scenario will be the same and same config will be used.
1 2 3 4 5 6 7 8 9 10 |
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); } } |
XmlWebApplicationContext: It can be used only in web applications, and it loads the config file from web app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.XmlWebApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new XmlWebApplicationContext(); FileExt fileExtension = (FileExt)context.getBean("FileExtBean"); //Code goes here to handle according to file extension } } |
Bean Factory
Defined in org.springframework.beans.factory.BeanFactory interface, BeanFactory provides support for Dependency Injection. Like in factory pattern, in which same type of object/bean created, BeanFactory comes with a feature which can create objects/beans of different types.
Lets stick to the same example what we have discussed in ApplicationContext, lets see how code of BeanFactory look like:
1 2 3 4 5 6 7 8 9 10 11 |
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { BeanFactory beanFactory = new XmlBeanFactory( new ClassPathResource("beans.xml")); } } |
It will load the bean using classpath resource.
Now see how to get the value that we defined in config file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { BeanFactory beanFactory = new XmlBeanFactory( new ClassPathResource("beans.xml")); FileExt fileExtBean = (FileExt) beanFactory.getBean("FileExtBean"); fileExtBean.getFileExtension(); //Stuff to handling according to file extension goes here } } |
Running the program will load the config file and gets the extension.
Now onward, the following three MVC Interview Questions for Java Spring are related to Spring Beans.
What are Spring Beans? How do we add a bean in Java Spring Application?
Spring bean is a java object when we see from a very high level. These are the core parts of our application which are managed by spring container. A spring bean is an object which is created, assembled and managed by spring container. These are created by the config file and the required data that is needed to create the bean. Config files are managed by spring container and based on these config file container creates the beans. Spring container provides the dependencies and other configurations that will be injected to bean, as well as the scope of objects that will be created.
To create/add a bean in spring, we need to provide the bean metadata to container using config files. Below is the example to create a simple bean, called Student, that has two properties, name and age.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Student{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
Above is the java code for a simple bean. Lets see how it will goes with config file:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="studentBean" class="Student"> <property name="name" value="Ahmad"/> <property name="age" value="12"/> </bean> </beans> |
How to define a Bean Scope in Spring Framework?
Spring Framework provides different types of scopes to beans, with which we can control the behavior and object instantiation. Below are the scope that Spring MVC Framework provides to a bean:
- Singleton : Singleton is the default scope and as the name suggests container will create a single instance per IoC container.
- Request : Container will instantiate bean for HTTP request. This scope can only be used for the HTTP requests, hence it will be applicable wherever the web-aware application.
- Prototype: Prototype scope enables any number of bean instances, when and where ever requested.
- Session : Beans configured with session scope, lives with the HTTP session. Similar to request it will also be applicable to web-aware application.
- Global_session : Global session scope is much more similar to session scope, only difference with this is Portlet web applications.
Lets take an example of how to define scope with a bean.
We can define scope of bean by two ways.
- In the bean definition tag itself, For Example:
1 |
<bean id="id of bean" class=”name of class” scope=" "> |
- Using @Scope annotation for annotation based configuration.
What are Inner Beans in Java Spring Framework?
Inner beans concept is much more similar like inner classes concept in java. Wherein a class can be defined under a class. Similarly a bean can also be defined under a bean. The inner bean is supported in both setter <property> and constructor <constructor-arg> injectors.
Lets take an example how inner beans can be created. We have defined a simple class Student and Address bean will be injected in this class by setter injection. Lets see how it will look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class Student{ private String name; private Address address; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Address{ private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } |
The config file will have the Address bean injected in the Student bean, lets see how :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="StudentBean" class="com.springmvc.docs.Student"> <property name="address" ref="AddresBean" /> </bean> <bean id="AddressBean" class="com.springmvc.docs.Address"> <property name="address" value="N 28/7" /> </bean> </beans> |
More Advanced MVC Interview Questions on Java Spring Framework
Explain in detail about Bean life cycle in Spring framework with the help of a diagram?
Spring framework provides several ways to control life cycle of a bean:
- Using callback interfaces (InitializingBean and DisposableBean)
- Using Aware interfaces
- Using init()/destroy() method in config file
- Using annotations (@PostConstruct and @PreDestroy)
Before digging into all of these, lets look at the life cycle methods with a diagram, below is the flow with with bean life cycle goes:
Using callback interfaces (InitializingBean and DisposableBean)
To initializate bean InitalizingBean interface needs to be implemented which is defined under org.springframework.beans.factory package. It declares a single method afterPropertiesSet(). Bean that implementing this interface required to provide implementation of afterPropertiesSet() and any initlization related code should be added in it.
To destroy bean DisposableBean interface needs to be implemented which is defiled under org.springframework.beans.factory package. It declares a single method destroy(). Bean that implementing this interface required to provide implementation of destroy() method, which will be executed when bean is destroyed.
Method signature for both looks like:
1 2 3 |
void afterPropertiesSet() throws Exception; void destroy() throws Exception; |
However this approach is not recommended to use, since bean class gets tightly coupled by spring container.
Code example would look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; public class DemoBean implements InitializingBean,DisposableBean{ //Other Bean Stuff goes here @Override public void afterPropertiesSet() throws Exception { //initialization code goes here } @Override public void destroy() throws Exception { //cleanup code } } |
Using Aware interfaces
There might be a case when a bean require certain infrastructure dependency. To achive this spring provides a number of aware interfaces. Each interface provides method to inject dependency in the bean, that we need to implement.
Let’s take example of one of the aware interfaces that is ApplicationContextAware which provides setApplicationContext() method that can be used to set the application instance to bean:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class DemoBean implements ApplicationContextAware { //Other Bean Stuff goes here @Override public void setApplicationContext(ApplicationContext application Context) throws BeansException { //code goes here to set application context } } |
Using init()/destroy() method in config file
As we discussed above in approach #1 using InitializingBean, DisposableBean interfaces, that is easy to use but has a drawback of having tight coupling. An alternative and to overcome this, spring provides yet another way to use init and destroy method in config file. There are two ways to define these:
- Local definition: As the name suggests, Local definition will be applicable to single bean. Below is the example for the same, how it will look in beans.xml.
123<beans><bean id="myLocalDemoBean" class="com.springmvc.docs.DemoBean" init-method="myInit" destroy-method="myDestroy"></bean></beans> - Global definition: Using global definition, methods will be invoked to all beans defined under the tag. Below is the example for the same, how it will look in beans.xml:
123<beans default-init-method="myInit" default-destroy-method="myDestroy"><bean id="myGlobalDemoBean" class="com.springmvc.docs.DemoBean"></bean></beans>
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class DemoBean { //Other Bean Stuff goes here public void myDestroy() throws Exception { //custom destroy method of bean } public void myInit() throws Exception { //custom Init method of bean } } |
Using annotations (@PostConstruct and @PreDestroy)
Spring 2.5 onwards, we can use annotations to control life cycle of bean, that are @PostConstruct and @PreDestroy.
Method annotated with @PostConstruct method will be invoked after the default constructer of bean has been called and before bean’s instance is returned to requesting object.
Method annotated with @PreDestroy will be called just before the it is destroyed inside bean container.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class DemoBean { //Other Bean Stuff goes here @PostConstruct public void myInit() { //Bean init code goes here } @PreDestroy public void myDestroy() { //Bean clean up code goes here } } |
Hopefully, this Spring MVC Interview Question has explained in detail all about bean life cycle with the help of source code.
Back to top
What is Bean Factory? How to use XMLBeanFactory? Explain with the help of a practical example?
Bean Factory
Defined in org.springframework.beans.factory.BeanFactory interface, BeanFactory provides support for Dependency Injection. Like in factory pattern, in which same type of object/bean created, BeanFactory comes with a feature which can create objects/beans of different types. There are several implementations of BeanFactory, XMLBeanFactory is one of them.
Lets see with a practical example how we can use XMLBeanFactory:
Suppose a scenario where in type of database will be passed to DAO layer using the config file and based on type of the database some post processing will be done. Lets see how we can achieve the same using XMLBeanFactory.
First thing we need to create is a class within which the property needs to be set. Lets create a DataBaseType.java class:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class DataBaseType{ private String databaseType; public String getDatabaseType() { return databaseType; } public void setDatabaseType(String databaseType) { this.databaseType = databaseType; } } |
Now lets create the config file named Bean.xml, from which we will set the database type
1 2 3 4 5 6 7 8 9 10 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="databasetype" class="com.springmvc.docs.DataBaseType"> <property name="databaseType" value="oracle"/> </bean> </beans> |
Lets see all together in action with XMLBeanFactory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.docs.springmvc; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml")); DataBaseType dbType = (DataBaseType) factory.getBean("databasetype"); String databaseType = dbType.getDatabaseType(); } //Post processing stuff of databasetype goes here ...... } |
What all we have done here:
- First we have created a factory object, with help of XmlBeanFactory and used ClassPathResource() to load the config file from the classpath.
- Once the config file will be loaded, we need to get the bean within which the property is defined. We have achieved this using getBean() method. This method used the bean id to get the generic object. Which is later on casted to original object.
- Once we got the object we used the getter method to get the property what we need.
What are the differences between Singleton and Prototype Bean? Give an example of using both?
If we look at both Singleton and Prototype Bean, both comes under the scope of bean. The most basic difference between both is, Singleton, as name suggests there will be only once instance of bean per IoC container, where as in case of prototype bean one can create as many number of bean instances as needed.
Lets take both of them one by one using some examples:
Singleton:
When a bean is declared as singleton, container will create only one instance of that bean and all calling beans will get the same instance matching the bean id and that particular instance will be returned by container. So whenever a bean is created with Singleton instance, exactly one instance of the object will be created so all the calling bean definitions will get the same instance. What container does is whenever a bean with singleton scope is created the instance is kept in cache and the same instance is returned to all requests.
The singleton scope is default scope of bean. Lets see how to create this:
1 2 3 4 5 |
<bean id="databaseType" class="com.springmvc.docs.DataBaseType"/> <bean id="databaseType" class="com.springmvc.docs.DataBaseType" scope="singleton"/> <bean id="databaseType" class="com.springmvc.docs.DataBaseType" singleton="true"/> |
What we have done is, we have created a bean databaseType with singleton scope. We can achieve this by any of these.
Lets create a config file and corresponding java file to see, how it looks like:
1 2 3 4 5 6 7 8 9 10 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="databasetype" class="com.springmvc.docs.DataBaseType" scope=”singleton”> <property name="databaseType" value="oracle"/> </bean> </beans> |
Java class of bean type looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class DataBaseType{ private String databaseType; public String getDatabaseType() { return databaseType; } public void setDatabaseType(String databaseType) { this.databaseType = databaseType; } } |
Now lets create a Main class and try to create some objects and see if they are equal:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.docs.springmvc; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml")); DataBaseType dbTypeObject1 = (DataBaseType) factory.getBean("databasetype"); DataBaseType dbTypeObject2 = (DataBaseType) factory.getBean("databasetype"); if(dbTypeObject1 == dbTypeObject2){ System.out.println("Both objects are equal"); } } } |
Running the above code what we get in output is:
Both objects are equal
And the reason why we got this output is because the scope is singleton and only one instance is created and passed by the container.
Prototype
Prototype is yet another scope of bean provided by spring framework. Where Singleton provides one and only instance, prototype scope says there will as many number of instances will provided, where and when needed. To create beans with prototype scope, we can use either of both ways that are listed below:
1 2 3 |
<bean id="databasetype" class="com.springmvc.docs.DataBaseType" scope="prototype"/> <bean id="databasetype" class="com.springmvc.docs.DataBaseType" singleton="false"/> |
Lets take the same example that we taken for Singleton. I am not writing code for java class of DataBaseType, since it will be same.
Lets create a config file and corresponding java file to see, how it looks like:
1 2 3 4 5 6 7 8 9 10 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="databasetype" class="com.springmvc.docs.DataBaseType" scope=”prototype”> <property name="databaseType" value="oracle"/> </bean> </beans> |
Now lets create a Main class and try to create some objects and see if they are equal or not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.docs.springmvc; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml")); DataBaseType dbTypeObject1 = (DataBaseType) factory.getBean("databasetype"); DataBaseType dbTypeObject2 = (DataBaseType) factory.getBean("databasetype"); if(dbTypeObject1 != dbTypeObject2){ System.out.println("Both objects are different"); } } } |
Running the example above what we got in result is:
Both objects are different
And this is expected since beans with prototype scope will have the different instance on each and every call.
What is AOP (Aspect Oriented Programming)? Explain in detail with the help of an example? Explain more related concepts including Aspect, Advice, JointPoint, PointCut and Advice Argument etc.
AOP, Aspect Oriented Programming, is a programming technique that provides modularity. What AOP does is, it brakes the program logic into different distinct parts what is called as concerns and it is used to achieve modularity using cross cutting concerns.
Lets try to understand the concept with an example.
Suppose there is mail delivery system, which has a service with multiple methods. Each method’s responsibility is to check the content of mail, lets day one method will check if it is spam or not, one will check if the content is not harmful to the system it is being routed to. Each method logs some and send confirmation to the message client if everything goes fine. Now if you see in each method, there is some logging, so you need to write code for logging in each and every method. Lets suppose a solution which enables you to write a centralized code for logging. Also lets suppose if client says I don’t want any confirmation from methods, so we need to remove the code from all the methods. Which increases the maintainability of code.
What AOP provides us is, AOP separates the concerns like logging, confirmation to client. It separates the concerns and enables you to write all these stuff in a config xml file. Sounds great isn’t it. That’s the beauty of AOP.
There are multiple concepts of AOP, these are listed below:
- Join point : A Join point is point in a class such as execution of a class or exception handling or so. Spring AOP supports only execution of a class as join point.
- Advice : Advice is something, that is the action been taken on a particular join point. These are actions that will be executed once program reaches a particular join point. They can be executed before, after, after and before both or on some exception scenario.
- Pointcut : Pointcut are different type of expressions that are matched on a join point, deciding factor for an advice needs to be run or not.
- Introduction : There may be scenarios where at a particular advice to add some methods, Introduction enables this thing.
- Target Object : As name suggests target objects are the objects on which the advice is applied. In spring AOP is implemented using Proxy pattern so the target objects are proxy objects only.
- Aspect : Aspect is a class that has the ability to cut the concerns. In simple words a class which has JoinPoint, Advice. This class is configured through a xml configuration or annotation based approach.
- AOP Proxy : AOP proxy is used to create proxy classes with target classes. Spring used JDK dynamic proxy to achive this.
- Weaving : Weaving as the name suggests, it is used for linking. Liking of other objects with the aspects. This can be done at runtime, complietime and on class loading. Spring performs weaving at compile time.
AOP implementations are provided by SpringAOP, AspectJ, JBoss AOP.
How to setup LDAP authentication using Spring Framework? Explain all steps with proper diagram.
LDAP is LightWeightApplicationProtocol that is a protocol for reading and editing directories over IP network. Lets quickly go through some LDAP terminology that we will be using.
- Ou – Organization Unit
- Dn – Distinguished name, which is used to find a person in LDAP server
- Bind – In this LDAP clients send bind request to LDAP server using credentials.
- Search – In this Distinguished name of user is retrieved using credentials.
- Root – it is root element of Ldap directory.
- BaseDn – BaseDn is a branch in LDAP tree, that is used for LDAP search.
LDAP authentication with spring:
Now lets go through the steps how we can achieve LDAP authentication using spring. First of first thing that we need to do is to add the dependencies to project. Spring ldap and spring security are the dependencies that we need to add to achieve LDAP authentication.
After having dependencies in place, we need to configure the Ldap server. Lets see how to do this:
1 |
<security:ldap-server url="ldap://springmvcdoc.edu:3679/dc=springmvcdoc,dc=edu" manager-dn="admin@spirngmvcdoc.edu" manager-password="secret"/> |
To perform Ldap search service must have the LDAP account, this is the reason we have provided manager-dn and manager-password. From the xml code written above application binds itself to LDAP server.
1 |
ldapTemplate.authenticate("dc=springmvcdoc,dc=education", filter.toString(), password); |
Authenticate method will return true or false based on the active directory search.
Alternate approach to this is to use ActiveDirectoryLdapAuthenticationProvider. Below is the example of how it will be used to authenticate:
1 2 3 4 5 6 7 8 |
<security:authentication-manager erase-credentials="true"> <security:authentication-provider ref="ldapActiveDirectoryAuthProvider"/> </security:authentication-manager> <bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider"> <constructor-arg value="springmvcdoc.edu" /> <constructor-arg value="ldap://springmvcdoc.edu/" /> </bean> |
Hopefully, this MVC Interview Questions or FAQs (Frequently Asked Questions) will be helpful for developer to grasp Java Spring Framework in more details. Continue with next part in this series on Java Spring MVC Interview Questions and Answers.
Top Web Developer Interview Questions and Answers Series:
- Top 20 AngularJS Interview Questions
- Top 15 Bootstrap Interview Questions
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET AJAX Interview Questions
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions