05 Nov
05Nov
@Required Annotation

If you want any dependency to be mandatory then just mention the @Required annotation

For ex. in Shape class i want Center to be passed then we do this by to avoid nullpointerexception.

@Required
public void setCenter(Point center){
this.center = center;
}

We also need BeanPostProcessor since its the BeanPostProcessor which does the validation at the
backend. If the bean Post processor it checks for all the intialization before and checks whether the
requirements are met or not.

in bean definition id refers to byName and byType refers to class. If it find multiple type then it will look for the name

With qualifier we can tell with which we need to map it.

@Autowired
@Qualifier("circleRelated")
public void setCenter(Point center){
this.center = center;
}
The above annotation takes care of all the BeanPostProcessor
JSR 250 - Java specification request Annotation is a specification that will apply
across all the Different techonologies.
@Resource Annotation Does Injection dependency which is related to the Java not spring specific.
@Resource
public void setCenter(Point center){
this.center = center;
}
@PostConstruct
public void intializeCircle(){
System.out.println("Init of Circle");
}

@PreDestroy
public void destriyCircle(){
System.out.println("Destroy of circle");
}

AbstractApplicationContext context = new ClassPathApplicationContext("Spring-config.xml");
context.registerShutDownHook();

We need to tell what particular class are bean so add @Component which defines the class to be Spring Bean. Its equivalen to definfing the bean

Spring Bean LifeCycle callbacks


package com.zest.spring;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Triangle implements InitializingBean, DisposableBean{

private Point pointA;
private Point pointB;
private Point pointC;


public Point getPointA() {
return pointA;
}
public void setPointA(Point pointA) {
this.pointA = pointA;
}
public Point getPointB() {
return pointB;
}
public void setPointB(Point pointB) {
this.pointB = pointB;
}
public Point getPointC() {
return pointC;
}
public void setPointC(Point pointC) {
this.pointC = pointC;
}

public void draw(){
System.out.println("Point A = ("+getPointA().getX()+" , "+getPointA().getY()+ ")");
System.out.println("Point B = ("+getPointB().getX()+" , "+getPointB().getY()+ ")");
System.out.println("Point C = ("+getPointC().getX()+" , "+getPointC().getY()+ ")");

}
public void destroy() throws Exception {
System.out.println("After Properties destroy");
// TODO Auto-generated method stub

}
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("Before INtialization set");
}
}

Or we can aceive the same thing from Spring-Config.xml

 destroy-method="myDestroy">        


Spring Framework

Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc. The framework, in broader sense, can be defined as a structure where we find solution of the various technical problems.

Inversion Of Control (IOC) and Dependency Injection

These are the design patterns that are used to remove dependency from the programming code. They make the code easier to test and maintain.

Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if our logic is moved to new environment.
In Spring framework, IOC container is responsible to inject the dependency. We provide metadata to the IOC container either by XML file or annotation.  

Advantage of Dependency Injection
  • makes the code loosely coupled so easy to maintain
  • makes the code easy to test
Advantages of Spring Framework

Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need to write too much code. It hides the basic steps of these technologies.

Let's take the example of JdbcTemplate, you don't need to write the code for exception handling, creating connection, creating statement, committing transaction, closing connection etc. You need to write the code of executing query only. Thus, it save a lot of JDBC code.

Loose Coupling

The Spring applications are loosely coupled because of dependency injection.

Easy to test

The Dependency Injection makes easier to test the application. The EJB or Struts application require server to run the application but Spring framework doesn't require server.

Lightweight

Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.

Fast Development

The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy development of JavaEE application.

Powerful abstraction

It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA

Declarative support

It provides declarative support for caching, validation, transactions and formatting.

Spring Module

The Spring framework comprises of many modules such as core, beans, context, expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc. These modules are grouped into Test, Core Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC / Remoting) as displayed in the following diagram.



IoC Container

The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets informations from the XML file and works accordingly. The main tasks performed by IoC container are:

  • to instantiate the application class
  • to configure the object
  • to assemble the dependencies between the objects

There are two types of IoC containers. They are:

  1. BeanFactory
  2. ApplicationContext
Difference between BeanFactory and the ApplicationContext

The org.springframework.beans.factory.BeanFactory and the org.springframework.context.ApplicationContext interfaces acts as the IoC container. The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.

Using BeanFactory

The XmlBeanFactory is the implementation class for the BeanFactory interface. To use the BeanFactory, we need to create the instance of XmlBeanFactory class as given below:

Resource resource=new ClassPathResource ("applicationContext.xml ");  
BeanFactory factory=new XmlBeanFactory (resource);  

The constructor of XmlBeanFactory class receives the Resource object so we need to pass the resource object to create the object of BeanFactory.

Using ApplicationContext

The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface. We need to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext as given below:

ApplicationContext context =  
new ClassPathXmlApplicationContext("applicationContext.xml");
Dependency Injection

Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled.

The Dependency Injection is a design pattern that removes the dependency of the programs. In such case we provide the information from the external source such as XML file. It makes our code loosely coupled and easier for testing.

Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency

  • By Constructor
  • By Setter method
Dependency Injection using Constructor
Constructor Injection with Dependent Object

If there is HAS-A relationship between the classes, we create the instance of dependent object (contained object) first then pass it as an argument of the main class constructor. Here, our scenario is Employee HAS-A Address. The Address class object will be termed as the dependent object.

public Employee(int id, String name, Address address) {  
super();  
this.id = id;  
this.name = name;  
this.address = address;  
}          
Constructor Injection with Collection Example

We can inject collection values by constructor in spring framework. There can be used three elements inside the constructor-arg element.

It can be:
  • list
  • set
  • map
public Question(int id, String name, List answers) {  
super();  
this.id = id;  
this.name = name;  
this.answers = answers;  
}  
Java is a programming language  
Java is a Platform  
Java is an Island of Indonasia  
Constructor Injection with Non-String Collection (having Dependent Object) Example

If we have dependent object in the collection, we can inject these information by using the ref element inside the list, set or map.

public Question(int id, String name, List answers) {  
super();  
this.id = id;  
this.name = name;  
this.answers = answers;  
}  
public Answer(int id, String name, String by) {  
super();  
this.id = id;  
this.name = name;  
this.by = by;  
}  
Constructor Injection with Map Example

we are using map as the answer that have answer with posted username. Here, we are using key and value pair both as a string.


public Question(int id, String name, Map answers) {  
super();  
this.id = id;  
this.name = name;  
this.answers = answers;  
}  
Constructor Injection with Non-String Map (having dependent Object) Example

In this example, we are using map as the answer that have Answer and User. Here, we are using key and value pair both as an object. Answer has its own information such as answerId, answer and postedDate, User has its own information such as userId, username, emailId.


public Question(int id, String name, Map answers) {  
super();  
this.id = id;  
this.name = name;  
this.answers = answers;  
}  

public Answer(int id, String answer, Date postedDate) {  
super();  
this.id = id;  
this.answer = answer;  
this.postedDate = postedDate;  
}  

public User(int id, String name, String email) {  
super();  
this.id = id;  
this.name = name;  
this.email = email;  
}  

Inheriting Bean in Spring

By using the parent attribute of bean, we can specify the inheritance relation between the beans. In such case, parent bean values will be inherited to the current bean.


Employee.java
This class contains three properties, three constructor and show() method to display the values.

public Employee() {}  

public Employee(int id, String name) {  
super();  
this.id = id;  
this.name = name;  
}  
public Employee(int id, String name, Address address) {  
super();  
this.id = id;  
this.name = name;  
this.address = address;  
}  


Address.java
public Address(String addressLine1, String city, String state, String country) {  
super();  
this.addressLine1 = addressLine1;  
this.city = city;  
this.state = state;  
this.country = country;  
}


1. What is Spring?
Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
 What are features of Spring?

Lightweight:Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.

Inversion of control (IOC):Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

Aspect oriented (AOP):Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.

Container:Spring contains and manages the life cycle and configuration of application objects.

MVC Framework:Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.

JDBC Exception Handling:The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.

Transaction Management:Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring’s transaction support is not tied to J2EE environments and it can be also used in container less environments.


Describe the Spring Framework?
The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications – on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the “plumbing” of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.
What is Spring Java Based Configuration?

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

for example:Annotation @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells spring that a method annotated with @Bean will return an object that should be registered as a bean in the spring application context.

Describe some of the standard Spring events?

Spring provides the following standard events:

  • 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.
  • ContextStartedEvent: This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. the user can poll their database or they can re/start any stopped application after receiving this event.
  • ContextStoppedEvent: This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. the users can do required housekeep work after receiving this event.
  • 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.
  • RequestHandledEvent: This is a web-specific event telling all beans that an HTTP request has been serviced.
Which are the Spring framework modules?

The basic modules of the Spring framework are :

  • Core module
  • Bean module
  • Context module
  • Expression Language module
  • JDBC module
  • ORM module
  • OXM module
  • Java Messaging Service(JMS) module
  • Transaction module
  • Web module
  • Web-Servlet module
  • Web-Struts module
  • Web-Portlet module
What are the types of Dependency Injection Spring supports?

Setter Injection : Setter-based DI is realized by calling setter methods on the user’s beans after invoking a no-argument constructor or no-argument static factory method to instantiate their bean.

Constructor Injection:  Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.

What is Spring IOC container?
The Spring IOC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The spring container uses dependency injection (DI) to manage the components that make up an application.
What are Spring beans?
The objects that form the backbone of the users application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that the users supply to the container.
What bean scopes does Spring support? Explain them.

The Spring Framework supports following five scopes, three of which are available only if the users use a web-aware Application Context.

Singleton: This scopes the bean definition to a single instance per Spring IoC container.

Prototype: This scopes a single bean definition to have any number of object instances.

Request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext

Session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

Global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

Explain Bean lifecycle in Spring framework?

Following is sequence of a bean lifecycle in Spring:

  • Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.
  • Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.
  • Set Bean Name: If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
  • Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
  • Pre Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
  • Initialize beans: If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
  • Post Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  • Ready to use: Now the bean is ready to use by the application
  • Destroy: If the bean implements DisposableBean , it will call the destroy() method

What is dependency injection(IOC) in Spring?

The basic concept of the dependency injection (also known as Inversion of Control pattern) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

What are ways to inject dependency in Spring?

There are two ways to do dependency injection in Spring.

What is Bean in Spring?

A normal POJO class managed by Spring IOC container are called Spring beans. It is core part of Spring application.
What is the difference between @Controller and @RestController in Spring MVC? 
Even though both are used to indicate that a Spring bean is a Controller in Spring MVC setup, @RestController is better when you are developing RESTful web services using Spring MVC framework. It's a combination of @Controller + @ResponseBody annotation which allows the controller to directly write the response and bypassing the view resolution process, which is not required for RESTful web service.
It also instructs DispatcherServlet to use different HttpMessageConverters to represent the response in the format client is expecting e.g. HttpMessageJackson2Convert to represent response in JSON format and JAXB based message converts to generate XML response.
You can further see  REST with Spring course by Baeldung to learn more about developing RESTful Web Services using Spring 4 and Spring 5.


What is the difference between a singleton and prototype bean?
This is another popular spring interview questions and an important concept to understand. Basically, a bean has scopes which define their existence on the application.

Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.

Whatever beans we defined in spring framework are singleton beans.
There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean.  By default, it is set to true. So, all the beans in spring framework are by default singleton beans.

What is the role of DispatcherServlet in Spring MVC?
The DispatcherServlet is very important from Spring MVC perspective, it acts as a FrontController i.e. all requests pass through it. It is responsible for routing the request to the controller and view resolution before sending the response to the client. When Controller returns a Model or View object, it consults all the view resolvers registered to find the correct type of ViewResolver which can render the response for clients.

In case of RESTful Web Services, the DispatcherServlet is also responsible for using HttpMessageConverter to represent the response in the JSON, XML, or TEXT format, depending on the content negotiation between Client and Server e.g. if client send request with HTTP accept header as "application/json" then DispatcherServlet will ask the HttpMessageJackson2Converter to convert the response into JSON format.


Difference between the setter and constructor injection in Spring?
Setter injection is more flexible than constructor injection because you must remember the type and order of constructor parameter. Also, constructor injection is generally used to inject the mandatory dependency, while setter can be used to inject optional dependency.
What type of transaction Management Spring support?
This spring interview question is a little difficult as compared to previous questions just because transaction management is a complex concept and not every developer familiar with it. Transaction management is critical in any applications that will interact with the database.
The application has to ensure that the data is consistent and the integrity of the data is maintained.  Following two types of transaction management is supported by spring:

1. Programmatic transaction management

2. Declarative transaction management.

How do you define the scope of a bean?

When defining a in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’s scope attribute to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the bean scope attribute must be set to singleton.

What are inner beans in Spring?

When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration metadata provides the use of element inside the or elements of a bean definition, in order to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.

How can you inject a Java Collection in Spring?

Spring offers the following types of collection configuration elements:

  • The type is used for injecting a list of values, in the case that duplicates are allowed.
  • The type is used for wiring a set of values but without any duplicates.
  • The type is used to inject a collection of name-value pairs where name and value can be of any type.
  • The type can be used to inject a collection of name-value pairs where the name and value are both Strings.

What is bean wiring?

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.

What is bean auto wiring?

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 BeanFactory without using and elements.

Are there limitations with autowiring?

Limitations of autowiring are:

  • Overriding: You can still specify dependencies using and settings which will always override autowiring.
  • Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
  • Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

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

Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations.
An example is the @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.

What is Annotation-based container configuration?

An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

How do you turn on annotation wiring?

Annotation wiring is not turned on in the Spring container by default. In order to use annotation based wiring we must enable it in our Spring configuration file by configuring element.

@Required annotation

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.

 @Autowired annotation

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

@Qualifier annotation

When there are more than one beans of the same type and only one is needed to be wired with a property, the @Qualifier annotation is used along with @Autowired annotation to remove the confusion by specifying which exact bean will be wired.

What is Spring MVC framework?

Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.

DispatcherServlet

The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.

WebApplicationContext

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with.

What is Controller in Spring MVC framework?

Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

@Controller annotation

The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.

@RequestMapping annotation

@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

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

@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.

@Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and makes the unchecked exceptions eligible for translation into Spring DataAccessException.


What are the major features in different versions of Spring Framework?

VersionLogoFeature
Spring 2.5spring 2.5 logo - Spring Interview Questions - Edureka!This version was released in 2007. It was the first version which supported annotations.
Spring 3.0spring 3.0 logo - Spring Interview Questions - Edureka!This version was released in 2009. It made full-fledged use of improvements in Java5 and also provided support to JEE6.
Spring 4.0Spring 4.0 logo - Spring Interview Questions - Edureka! This version was released in 2013. This was the first version to provide full support to Java 8.

Differentiate between constructor injection and setter injection.

Constructor InjectionSetter Injection
There is no partial injection.There can be partial injection.
It doesn’t override the setter property.It overrides the constructor property.
It will create a new instance if any modification is done.It will not create new instance if any modification is done.
It works better for many properties.It works better for few properties.

Differentiate between BeanFactory and ApplicationContext.


BeanFactoryApplicationContext
It is an interface defined in org.springframework.beans.factory.BeanFactoryIt is an interface defined in org.springframework.context.ApplicationContext
It uses Lazy initializationIt uses Eager/ Aggressive initialization
It explicitly provides a resource object using the syntaxIt creates and manages resource objects on its own
It doesn’t supports internationalizationIt supports internationalization 
It doesn’t supports annotation based dependency    It supports annotation based dependency  

List some of the benefits of IoC.

Some of the benefits of IoC are:

  • It will minimize the amount of code in your application.
  • It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.
  • It promotes loose coupling with minimal effort and least intrusive mechanism.
  • It supports eager instantiation and lazy loading of the services.

Explain Spring Beans?

  • They are the objects that form the backbone of the user’s application.
  • Beans are managed by the Spring IoC container.
  • They are instantiated, configured, wired and managed by a Spring IoC container
  • Beans are created with the configuration metadata that the users supply to the container.
  • Bean generation - Spring Interview Questions - Edureka!

What is the Bean life cycle in Spring Bean Factory Container?

Bean life cycle in Spring Bean Factory Container is as follows:

  1. The Spring container instantiates the bean from the bean’s definition in the XML file.
  2. Spring populates all of the properties using the dependency injection, as specified in the bean definition.
  3. The factory calls setBeanName() by passing the bean’s ID, if the bean implements the BeanNameAware interface.
  4. The factory calls setBeanFactory() by passing an instance of itself, if the bean implements the BeanFactoryAware interface.
  5. preProcessBeforeInitialization() methods are called if there are any BeanPostProcessors associated with the bean.
  6. If an init-method is specified for the bean, then it will be called.
  7. Finally, postProcessAfterInitialization() methods will be called if there are any BeanPostProcessors associated with the bean.

To understand it in better way check the below diagram:

beanLifeCycle - Spring Interview Questions - Edureka!


What is Tight Coupling?
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.
What is Loose Coupling?
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.
What are Beans in Spring?
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.
Explain Bean creation process?

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


What is the importance of the annotation @Primary
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.
What is Dependency Injection?
Dependency Injection is where Spring searches for beans; once the appropriate bean is found, it autowires 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 autowires them.
Explain Inversion of Control (IOC).
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.
What are the roles of an IOC (Inversion of Control) Container?

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)


What is Application Context?
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).
Explain the process of creating an ApplicationContext in Spring.
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.
Explain Component Scan.

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


How do you perform the same (above question) in Spring Boot?
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.
Differentiate @Component, @Repository and @Service and @Controller?
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.
List out the different scopes of Bean.

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


 What is Dirty Read?
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.
List out the new features available in Spring Framework 4.0 and Spring Framework 5.0?
Spring 4.0 is the first to support Java features. Spring 5.0 has the support for Reactive Programming and Kotlin.
What is a FrontController?
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.
What is a ViewResolver?
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.
List out all the concepts that are available in the MVC Architecture?
  1. The browser sends a request to DispatcherServlet
  2. DispatcherServlet knows the HanderMapping and can find the appropriate controllers
  3. Controllers execute the request and put the data in the model and return back the view name to the DispatcherServlet.
  4. DispatcherServlet uses the view name and ViewResolver to map to the view.
Explain Model Attribute?
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.
What is a Session Attribute?
The annotation @SessionAttributes (“argument”) is decorated on class (Controller). The attribute (argument) that is present in Model is available in the session.
Explain the @InitBinder?
This annotation is decorated on a method in which a date format is declared, and throughout the class, the defined date format is used. Whenever the binding happens with a date field @InitBinder; annotation says to use the CustomDateEditor, which in return uses the date format mentioned in @InitBinder.
Define @ControllerAdvice?
his annotation is used when logic needs to be implemented commonly in multiple classes (Controllers). For instance, if an Exception or its subclasses, or when an exception is raised in the classes, it will be handled by a method annotated with @ExceptionHandler. Whenever an exception occurs in any of the controllers, the exception is handled by the method annotated with @ExceptionHandler.
Why Spring Boot?
Spring-based applications have a lot of configuration (boiler-plate code). In Spring MVC, a lot of configuration is required (like component scan, dispatcher servlet, view resolver, etc). Whereas, in Spring Boot the boiler-plate code is not required.
Spring vs Spring MVC vs Spring Boot?

Spring: the most important feature of Spring is Dependency Injection or Inversion of Control.

Spring MVC: provides a decoupled approach in developing web applications. Concepts like DispatcherServlet, ModelAndView, ViewResolver makes web application development easy.

Spring Boot: makes the configuration very easy and automatic using a feature called Auto Configuration, in which the DispatcherServlet is done by Spring internally.

What is the role of @SpringBootApplication?

This annotation is used to launch up the entire application. Internally, @SpringBootApplication does the following,

@SpringBootConfiguration: same as @Configuration in a Spring Application.

@EnableAutoConfiguration: auto-configures the classes available in the classpath.

@ComponentScan: all the classes available under a package will be scanned when this annotation is applied.

What does an Embedded Server mean in Spring Boot?
To deploy any web application a server like Tomcat is required. In Spring Boot a server (like Tomcat) is available as part of the application in a jar. The concept of Embedded Server makes the deployment of application very easy and independent.
Why do we use application.properties?
The file application.properties is used to configure things like database details, log generation, security (username/password), serialization, etc.
What is Spring JDBC?
Spring JDBC uses methods like update (query), execute (query) and query (SQL, resultSetExtractor) to interact with the database.
What is the difference between JDBC and Spring JDBC?
In JDBC, the checked exceptions need to be written; whereas, in Spring JDBC those exceptions are made into Runtime Exceptions. Which means, exception handling is not manually done in Spring JDBC.
What is JPA?
Java Persistence API (JPA) defines the mapping from Java Object to a Database Table. The procedure to map a Java object to a row in a database table is defined in JPA. JPA provides a lot of useful annotations, using which the relationship between classes and tables are defined.
What is Hibernate?
Once the mapping is done, Hibernate (a JPA Implementation) will help us create query under the hood and interact with the database.
Describe the cases in which the Dependency Injection is done through Constructors and Setters?
When the dependencies are required/mandatory, the Constructor approach is selected. And when the dependencies are optional then the Setters approach is used.
What is the importance of POM.XML file?
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 , , , and a few more.
What does the @RequestParam annotation do?
This allows the server side to read from data and automatically bind it to a parameter coming into the method.
What is Spring Security?
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.
What is CSRF?
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.
BeanFactoryPostProcessor
BeanFactoryPostProcessor works on the bean definitions or configuration meta data of the bean before beans are actually created. Spring provides multiple BeanFactoryPostProcessor beans, so it invoked to resolve run time dependencies such reading value from external property files. In Spring application, BeanFactoryPostProcessor can modify the definition of any bean.

A   bean   factory    post-processor    is    a    java   class    which   implements   the org.springframework.beans.factory.config.BeanFactoryPostProcessor interface. It is executed manually (in the case of the BeanFactory) or automatically (in the case of the ApplicationContext) to apply changes of some sort to an entire BeanFactory, after it has been constructed.

 Spring includes a number of pre-existing bean factory post-processors, such as given below

PropertyResourceConfigurer and PropertyPlaceHolderConfigurer – implemented as a bean factory post-processor, is used to externalize some property values from a BeanFactory definition, into another separate file in Java Properties format. This is useful to allow to developer to declare some key property as properties file. As given below example show the database connection related information in the following property file.

Ref : https://www.dineshonjava.com/writing-beanfactorypostprocessor-in/


When to use Constructor and Setter Injection in Spring?
Whenever compulsory dependencies are there use the constructor DI.
Whenever the optional dependencies are there use the Setter DI
Spring dispatcher Servlet
The purpose of the dispatcher is to receive the requests and map those requests to the correct resources such as controllers, models and views.
In Spring web MVC framework, the mechanism of dispatching the request to the appropriate controllers is achieved by configuring the DispatcherServlet Class. Dispatcher servlet is the class which manages the entire request handling process.
Its view resolution strategy can be specified by a ViewResolver implementation resolving symbolic view names into view objects. Default is InternalResourceViewResolver.
ViewResolver objects can be added as beans in the application context, overriding the default view resolver.
View Resolver
All MVC frameworks for web applications provide a way to address views. Spring provides view resolvers, which enable you to render models in a browser without tying you to a specific view technology. Out of the box, Spring enables you to use JSPs, Velocity templates and XSLT views, for example.
The two interfaces which are important to the way Spring handles views are ViewResolver and View. The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies.

Resolving views - ViewResolver Interface

all controllers in the Spring Web MVC framework return a ModelAndView instance. Views in Spring are addressed by a view name and are resolved by a view resolver. Spring comes with quite a few view resolvers. We'll list most of them and then provide a couple of examples.

Table 16.4. View resolvers

ViewResolverDescription
AbstractCachingViewResolverAn abstract view resolver which takes care of caching views. Often views need preparation before they can be used, extending this view resolver provides caching of views.
XmlViewResolverAn implementation of ViewResolver that accepts a configuration file written in XML with the same DTD as Spring's XML bean factories. The default configuration file is /WEB-INF/views.xml.
ResourceBundleViewResolverAn implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified by the bundle basename. The bundle is typically defined in a properties file, located in the classpath. The default file name isviews.properties.
UrlBasedViewResolverA simple implementation of the ViewResolver interface that effects the direct resolution of symbolic view names to URLs, without an explicit mapping definition. This is appropriate if your symbolic names match the names of your view resources in a straightforward manner, without the need for arbitrary mappings.
InternalResourceViewResolverA convenience subclass of UrlBasedViewResolver that supports InternalResourceView (i.e. Servlets and JSPs), and subclasses such as JstlView and TilesView. The view class for all views generated by this resolver can be specified via setViewClass(..). See the Javadocs for the UrlBasedViewResolver class for details.
VelocityViewResolver /FreeMarkerViewResolverA convenience subclass of UrlBasedViewResolver that supports VelocityView (i.e. Velocity templates) orFreeMarkerView respectively and custom subclasses of them.

View Resolvers

All MVC frameworks provide a way of working with views.

Spring does that via the view resolvers, which enable you to render models in the browser without tying the implementation to a specific view technology.

The ViewResolver maps view names to actual views.

And the Spring framework comes with quite a few view resolvers e.g. InternalResourceViewResolver, XmlViewResolver, ResourceBundleViewResolver and a few others.


Add an InternalResourceViewResolver

This ViewResolver allows us to set properties such as prefix or suffix to the view name to generate the final view page URL.

@Bean

public ViewResolver internalResourceViewResolver() {

    InternalResourceViewResolver bean = new InternalResourceViewResolver();

    bean.setViewClass(JstlView.class);

    bean.setPrefix("/WEB-INF/view/");

    bean.setSuffix(".jsp");

    return bean;

}

@RequestBody || @ResponseBody
@RequestBody and @ResponseBody annotations are used to bind the HTTP request/response body with a domain object in method parameter or return type. Behind the scenes, these annotation uses HTTP Message converters to convert the body of HTTP request/response to domain objects.

@RequestBody - If a method parameter is annotated with @RequestBody, Spring will bind the incoming HTTP request body(for the URL mentioned in @RequestMapping for that method) to that parameter. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the HTTP request body into domain object [deserialize request body to domain object], based on Accept header present in request.

  • The Accept header is used by HTTP clients [browsers] to tell the server what content types they’ll accept.
  • The server sends back the response, which will include a Content-Type header telling the client what the content type of the returned content actually is. In case of POST or PUT request, browsers do send data in request, so they actually send content-type as well.

@RequestBody annotation. Thanks to this annotation, Spring will try to bind the request body [which can be JSON/XML/Other] to user object[ Means crating a new user object with the details found in the request body like user name,age etc..], based on Content-Type header in Http request.

But Spring need help to convert the request body into user object. It needs a converter which can convert the data in HTTP request body [which can be JSON/XML/Other] into user object.

Spring provides out-of-box many default HttpMessageConverters, which will be used for conversion, depending on presence of certain library in project classpath.

For example, if the Content-Type in request Header was one of application/json or application/xml , that means the POST body contains json or XML[Popular formats], and if Jackson library is found in your classpath, Spring will delegate the conversion to MappingJackson2HttpMessageConverter [for json] or MappingJackson2XmlHttpMessageConverter [for xml].

@ResponseBody

If a method is annotated with @ResponseBody, Spring will bind the return value to outgoing HTTP response body. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type present in request HTTP header.

@RequestMapping(value = "/user/all", method = RequestMethod.GET)

public @ResponseBody List listAllUsers() {

    return userService.findAllUsers();

}

This is the controller method to handle typical HTTP GET request [for URL /user/all] to retrieve all users. In this case, Spring will convert the user list into appropriate format [JSON/XML/Other] using available converters, based on content type.

NOTE : As from Spring 4, @RestController is the preferred way to achieve the same functionality earlier provided by @ResponseBody. Under the hood, @RestController is @Controller+@ResponseBody, and it avoids the need of prefixing every method with @ResponseBody. Next post goes into details with a full working example.

Default HttpMessageConverters

Spring provides out of box following Http message converters which implements HttpMessageConverter interface [Credit : Spring Reference].

  • StringHttpMessageConverter

    An HttpMessageConverter implementation that can read and write Strings from the HTTP request and response. By default, this converter supports all text media types ( text/*), and writes with a Content-Type of text/plain.

  • FormHttpMessageConverter

    An HttpMessageConverter implementation that can read and write form data from the HTTP request and response. By default, this converter reads and writes the media type application/x-www-form-urlencoded. Form data is read from and written into a MultiValueMap.

  • ByteArrayHttpMessageConverter

    An HttpMessageConverter implementation that can read and write byte arrays from the HTTP request and response. By default, this converter supports all media types ( */*), and writes with a Content-Type of application/octet-stream. This can be overridden by setting the supportedMediaTypes property, and overriding getContentType(byte[]).

  • MarshallingHttpMessageConverter

    An HttpMessageConverter implementation that can read and write XML using Spring’s Marshaller and Unmarshaller abstractions from the org.springframework.oxm package. This converter requires a Marshaller and Unmarshaller before it can be used. These can be injected via constructor or bean properties. By default this converter supports ( text/xml) and ( application/xml).

  • MappingJackson2HttpMessageConverter

    An HttpMessageConverter implementation that can read and write JSON using Jackson’s ObjectMapper. JSON mapping can be customized as needed through the use of Jackson’s provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports ( application/json).

  • MappingJackson2XmlHttpMessageConverter

    An HttpMessageConverter implementation that can read and write XML using Jackson XML extension’s XmlMapper. XML mapping can be customized as needed through the use of JAXB or Jackson’s provided annotations. When further control is needed, a custom XmlMapper can be injected through the ObjectMapper property for cases where custom XML serializers/deserializers need to be provided for specific types. By default this converter supports ( application/xml).

  • SourceHttpMessageConverter

    An HttpMessageConverter implementation that can read and write javax.xml.transform.Source from the HTTP request and response. Only DOMSource, SAXSource, and StreamSource are supported. By default, this converter supports ( text/xml) and ( application/xml).

  • BufferedImageHttpMessageConverter

    An HttpMessageConverter implementation that can read and write java.awt.image.BufferedImage from the HTTP request and response. This converter reads and writes the media type supported by the Java I/O API.
















Comments
* The email will not be published on the website.
I BUILT MY SITE FOR FREE USING