What is Spring?The Spring Framework is an open source application framework for the Java platform and .NET Framework (Spring.NET), its core features can be used by any Java application, its basically is a lightweight, inversion of control and aspect-oriented container framework.What are the features of Spring Framework?Spring Provides Better Leverage and layered architecture.* Spring Enables POJO Programming.* Dependency Injection Helps Testability.* Inversion of Control Simplifies tasks like JDBC.* Spring’s Community Thrives, better support , documentation etc.* Spring provides consistent & simple programming model making it an ideal architectural "glue."* Spring provides alternative or improvements for Enterprise components like JTA,JMS, Email etc.* Spring provides API abstraction , allowing to change the underlying implementation if needed.* Spring provides loose integration with a variety of technologies out of the box* Support for Programmatic or XML based or Annotation based configuration. What are the advantages of Spring framework?Ans: The advantages of Spring are as follows:* Spring has layered architecture. Use what you need and leave you don't need now.* Spring Enables POJO Programming. There is no behind the scene magic here. * POJO programming enables continuous integration and testability.* Dependency Injection and Inversion of Control Simplifies JDBC* Open source and no vendor lock-in.
IoC introduction
In traditional programming, the flow of the business logic is determined by objects that are statically assigned to one another. With inversion of control, the flow depends on the object graph that is instantiated by the assembler and is made possible by object interactions being defined through abstractions. The binding process is achieved through dependency injection, although some argue that the use of a service locator also provides inversion of control.
Inversion of control as a design guideline serves the following purposes:
- There is a decoupling of the execution of a certain task from implementation.
- Every module can focus on what it is designed for.
- Modules make no assumptions about what other systems do but rely on their contracts.
- Replacing modules has no side effect on other modules.
Differentiating with dependency injection
Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. Inversion of control relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality.
The two concepts work together in this way to allow for much more flexible, reusable, and encapsulated code to be written. As such, they are important concepts in designing object-oriented solutions.
Implementing inversion of control design pattern
In object-oriented programming, there are several basic techniques to implement inversion of control. These are:
- using a factory pattern
- using a service locator pattern
- using a dependency injection of any given below type:
- a constructor injection
- a setter injection
- an interface injection
IoC in spring framework
The
org.springframework.beans and
org.springframework.context packages provide the basis for the Spring Framework’s IoC container. The
BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The
ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring’s AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in web applications.
The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring.
There are a number of implementations of the BeanFactory interface. The most commonly used BeanFactory implementation is theXmlBeanFactory class. Other commonly used class is XmlWebApplicationContext. Depending on the bean definition, the factory will return either an independent instance of a contained object (the Prototype design pattern), or a single shared instance (a superior alternative to the Singleton design pattern, in which the instance is a singleton in the scope of the factory). Which type of instance will be returned depends on the bean factory configuration: the API is the same.
Before we dive into dependency injection types, let first identify the ways of creating a bean in spring framework as it will help in understanding the things in next section.
What is IOC (or Dependency Injection)?Ans:The basic concept of the Inversion of Control pattern (also known as dependency injection) 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.
Design Patterns Used in the Spring Framework ?
- Singleton Design Pattern – Beans defined in spring config files are singletons by default.
- Proxy Design Pattern - It is heavily used in Spring AOP, and remoting.
- Template method Design Pattern -It is used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc.). For example JdbcTemplate, JmsTemplate, JpaTemplate.
- Model View Controller
- Front Controller
- View Helper.
Difference between BeanFactory and ApplicationContext?
A BeanFactory is the simplest form of container, it pretty much just instantiates and configures beans.But when more advanced framework services are needed, Spring’s ApplicationContext is the container to use.Using Application context you can achieve Automatic BeanPostProcessor registration, Automatic BeanFactoryPostProcessor registration,Convenient MessageSource access (for i18n) and ApplicationEvent publication.
What are the different types of spring beans scopes?
Spring has five different types of bean scopes.
- Singleton – Scopes a single bean definition to a single object instance per Spring IoC container. It means that every time a request for this bean is made, same instance is returned.
- Prototype – Scopes a single bean definition to any number of object instances. it means that every time a request for this bean is made, a new instance is created.
- Request – Single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring Application Context.
- Session - single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring Application Context.
- Global session - Single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring Application Context.
7.Explain About Bean Lift Cycle?
1.First Spring container find the bean definition from context file and instantiates the bean.
2. Spring injects values and bean references into the bean’s properties.
3. If the bean implements BeanNameAware, Spring passes the bean’s ID to the set-
BeanName() method.
4. If the bean implements BeanFactoryAware, Spring calls the setBeanFactory() method, passing in the bean factory itself.
5. If the bean implements ApplicationContextAware, Spring will call the set ApplicationContext() method, passing in a reference to the enclosing application context.
6. If any of the beans implement the BeanPostProcessor interface, Spring calls their postProcessBeforeInitialization() method.
7 . If any beans implement the InitializingBean interface, Spring calls their afterPropertiesSet() method. Similarly, if the bean was declared with an init-method, then the specified initialization method will be called.
8. If there are any beans that implement BeanPostProcessor, Spring will call their postProcessAfterInitialization() method.
9. At this point, the bean is ready to be used by the application and will remain in the application context until the application context is destroyed.
10. If any beans implement the DisposableBean interface, then Spring will call their destroy() methods. Likewise, if any bean was declared with a destroy method, then the specified method will be called.
8.What is mean by Dependency Injection?
Writing the Java Classes which should be independent as independent as possible of other Java classes then only we can achieve loose coupling because loose coupling promotes greater reusability, easier maintainability.
Dependency Injection (IOC) is a technique or design pattern to achieve this loose coupling. You don’t need to create object or directly connect your components and services together in code you can describe which services are needed by which components in a configuration file then IOC container will take care of Object creation and dependency collaboration.
9.Different types of Dependency Injection?
Three Types of Dependency Injection are
1. Constructor Injection.
2. Setting Injection
3. Interface Injection.
10.What is Bean wiring and Different types?
Wiring is typically performed within a Spring container using an XML file. This XML file contains configuration information for all of the components of an application, along with information that helps the container perform DI to associate beans with other beans that they depend on.
byName —Attempts to match all properties of the autowired bean with beans
that have the same name (or ID) as the properties. Properties for which there’s
no matching bean will remain unwired.
byType — Attempts to match all properties of the autowired bean with beans
whose types are assignable to the properties. Properties for which there’s no
matching bean will remain unwired.
constructor — Tries to match up a constructor of the autowired bean with
beans whose types are assignable to the constructor arguments.
autodetect —Attempts to apply constructor autowiring first. If that fails,
byType will be tried.
11.Different Types of Spring Transaction Management ?
Transaction management is required to ensure the data integrity and consistency in database.Spring has two types Transaction management.
1.Declarative : Transaction is applied,instead of implementing in your business logic place that means with the help simple configuration you apply a common functionality across all your code.
2. Programmatic : When you add code some functionality by yourself so that you could control each and everything by yourself. This usually mixes the unrelated functionality in your business logic.
15.What is Spring AOP? What is PointCut?
The main strength Spring Framework is its robust and flexible aspect oriented programming infrastructure.Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects.
17.Different Types of Advice in Spring AOP?
1. Before advice – It will Run before the method execution.
2. After returning advice – It will Run after the method returns a result.
3. After throwing advice – It will Run after the method throws an exception.
4. Around advice – It will Run around the method execution and it combines all three advice’s above.
18.What is Around Advice?
Basic before and after advice have some limitations.Around Advice is combination of both Before and After Advice. Specifically, it’s tricky to share information between before advice and after advice without resorting to storing that information in member variables.Around advice has an advantage over before and after advice in this regard. With around advice, you can accomplish the same thing as you can with distinct before and after advice, but do it in a single method. Since the entire set of advice takes place in a single method, there’s no need to retain state in a member variable.
21.Explain Spring MVC Lifecycle?
1. The client sends a request to web container in the form of http request.This incoming request is intercepted by Front controller called DispatcherServlet.
2. DispatcherServlet tries to find out appropriate Handler Mappings.
3. With the help of Handler Mappings, the DispatcherServlet will dispatch the request to appropriate Controller.
4. The Controller tries to process the request and returns the Model and View object in form of ModelAndView instance to the Front Controller.
5. DispatcherServlet then tries to resolve the View (which can be JSP or Freemarker or Velocity etc) by with help of the View Resolver object.
6. Finally the selected view is then rendered back to client.