Spring Interview Question
What is Spring?
Ans. 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?
Ans. Spring Framework can be used for developing any JEE application. It can be described as complete and modular framework. Spring has below features: 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.
Q. What is difference between @Component, @Service, @Repository, @Controller Annotations?
Ans. Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework. @Component is a generic annotation. Difference of @Service, @Repository, @Controller with @Component is they are special cases of @Component and used for particular purposes. The difference is just classification only.
For all these annotations (stereotypes), technically the core purpose is same. Spring automatically scans and identifies all these classes that are annotated with @Component, @Service, @Repository, @Controller and registers BeanDefinition with ApplicationContext.
@Component - generic and can be used across application
@Service - annotate classes at service layer level.
@Controller - annotate classes at presentation layers level, mainly used in Spring MVC
@Repository - annotate classes at persistence layer, which will act as database repository.
As above said, technically there is no difference between them, all of the 3 annotations @Service, @Repository and @Controller implementations are annotated by @Controller annotation. So technically you can use @Controller for any auto component scan, but for better readability and better standards use respective annotations.
Q What is Spring Bean Life Cycle?
Ans. Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of a Spring bean is very easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required. There are also other activities between initialization and destruction of the bean. These activities take place behind the scenes. The following are the stages in a bean's lifecycle:
- The spring container finds the bean's definition from the XML file and instantiates the bean.
- Using the dependency injection, spring populates all of the properties as specified in the bean definition.
- If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID.
- If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
- If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
- If the bean implements IntializingBean,its afterPropertySet()method is called. If the bean has init method declaration, the specified initialization method is called.
- If an init-method is specified for the bean, it will be called.
- Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
- Bean is ready to use
- If the bean implements DisposableBean, the Spring IoC container will call the destroy() method . If a custom destroy () method is defined, the container calls the specified method.
Q. Explain Aware Interface in Spring
Ans. Spring offers a range of Aware interfaces that allow beans to indicate to the container that they require a certain infrastructure dependency. Each interface will require you to implement a method to inject the dependency in bean. Some Aware Interface is:
|ApplicationContextAware||Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.|
|ApplicationEventPublisherAware||Set the ApplicationEventPublisher that this object runs in.|
|BeanClassLoaderAware||Callback that supplies the bean class loader to a bean instance.|
|BeanFactoryAware||Callback that supplies the owning factory to a bean instance.|
|BeanNameAware||Set the name of the bean in the bean factory that created this bean.|
|MessageSourceAware||Set the MessageSource that this object runs in.|
|NotificationPublisherAware||Set the NotificationPublisher instance for the current managed resource instance.|
|ResourceLoaderAware||Set the ResourceLoader that this object runs in.|
|ServletConfigAware||Set the ServletConfig that this object runs in.|
|ServletContextAware||Set the ServletContext that this object runs in.|
Q. Difference Between BeanFactory and ApplicationContext
Ans. A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients. BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory. Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
- A means for resolving text messages, including support for internationalization.
- A generic way to load file resources.
- Events to beans that are registered as listeners.
- Application contexts provide a means for resolving text messages, including support for i18n of those messages.
- Application contexts provide a generic way to load file resources, such as images.
- Application contexts can publish events to beans that are registered as listeners.
- Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
- ResourceLoader support: Spring's Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
- MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable
Q. Different types of Controller in MVC?
Ans. In Spring mvc, DispatcherServlet acts as controller and it will call the methods of controller classes that we have defined. A controller class is the one which provides the implementation of org.springframework.web.servlet.mvc.Controller interface directly or indirectly. In spring we have bunch of controller classes implementing org.springframework.web.servlet.mvc.Controller interface. The DispatcherServlet always calls handleRequest() of Controller interface when ever we send request from the browser to the controller. Some of the controllers frequently used are :
AbstractController,AbstractCommandController,AbstractFormController, MultiActionController,SimpleFormController,AbstractWizardFormController... etc.
All of these classes are implementing Controller interface. If we want to write our own controller we can extend any one of these classes , so that our class will become a controller class.