What is a 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 J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
[dt_sc_button type=”type1″ link=”http://www.interviewgig.com/discussion-room/post-a-question/” size=”large” bgcolor=”#7ed640″ textcolor=”#ffffff” target=”_blank” timeline_button=”no”]Post a Question[/dt_sc_button]
What are some of the important features and advantages of Spring Framework?
Spring Framework is built on top of two design concepts – Dependency Injection and Aspect Oriented Programming.
Some of the features of spring framework are:
- Lightweight and very little overhead of using framework for our development.
- Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes care of wiring them together to achieve our work.
- Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
- Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
- Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.
Some of the advantages of using Spring Framework are:
- Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible for initializing resources or beans and injects them as dependencies.
- Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.
- Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.
- Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency in our project.
- Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies, for example there is a Spring project for Android to help us write better code for native android applications. This makes spring framework a complete package and we don’t need to look after different framework for different requirements.
What are the different modules in spring framework?
Following are the modules of the spring framework:
- 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
How do we implement DI in Spring Framework?
We can use Spring XML based as well as Annotation based configuration to implement DI in spring applications.
What is the difference between BeanFactory and ApplicationContext?
BeanFactory is the basic container whereas ApplicationContext is the advanced container. ApplicationContext extends the BeanFactory interface. ApplicationContext provides more facilities than BeanFactory such as integration with spring AOP, message resource handling for i18n etc.
What is Bean Factory?
Bean Factory is core of the spring framework and, it is a Lightweight container which loads bean definitions and manages your beans. Beans are configured using XML file and manage singleton defined bean. It is also responsible for life cycle methods and injects dependencies. It also removes adhoc singletons and factories.
Define Bean Wiring?
Bean wiring is the creation of associations between application components that are between the beans in a particular spring container.
Why Spring framework is needed?
Spring framework is needed because it is –
- Very Light Weight Container
- Framework
- IOC
- AOP
Define Application context module?
This is a very important module and supplies various necessary services like EJB integration, remoting, JNDI access and scheduling. It transforms spring into a framework. It also broadens the idea of BeanFactory by application of lifecycle events, providing support for internationalization messages and validation.
What is Auto Wiring?
Autowiring is used to build relationships between the collaborating beans. Spring container can automatically resolve collaborators for beans.
What are the different Modes of Autowiring?
Autowiring has five different modes:
No: no autowire
byName: Autowiring that can be done by property name
byType: property type as autowired
Constructor: It is similar to byType and it is property is in constructor
autodetect:Â Spring is allowed to select autowiring from byType or constructor
What are the methods of bean life cycle?
There are two important methods of Bean life cycle:
Setup called when bean is loaded into container
Teardown called when bean is unloaded into container
For More:
What are the different types of events of Listeners?
Following are the different types of events of listeners:
- ContextClosedEvent – This event is called when the context is closed.
- ContextRefreshedEvent – This event is called when context is initialized or refreshed
- RequestHandledEvent – This event is called when the web context handles request
What is a Joinpoint?
The point where an aspect can be introduced in the application is known as a joinpoint. This point could be a field being modified, a method being called or even an exception being thrown. At these points, the new aspect’s code can be added to introduce a new behavior to the application.
Aspect code can be inserted at this point into normal flow of application to change the current behavior.
What are the types of advice in AOP?
There are 5 types of advices in spring AOP.
- Before Advice
- After Advice
- After Returning Advice
- Throws Advice
- Around Advice
Name some of the important Spring Modules?
Some of the important Spring Framework modules are:
Spring Context – for dependency injection.
Spring AOP – for aspect oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
Define Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed when a specific join point with matching pointcut is reached in the application. You can think of Advices as Spring interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that is matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
Join Point: A join point is the specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join points is always the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where argument type is determined.
What are different scopes of Spring Bean?
There are five scopes defined for Spring Beans.
Singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
Prototype: A new instance will be created every time the bean is requested.
Request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
Session: A new bean will be created for each HTTP session by the container.
Global-session: This is used to create global session beans for Portlet applications.
How to handle exceptions in Spring MVC Framework?
Spring MVC Framework provides following ways to help us achieving robust exception handling.
Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.Â
What is IOC?
IoC stands for Inversion of control pattern. It is also known as dependency injection. The basic concept of the IOC 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.
What are the different types of Dependency Injection?
There are three types of dependency injection:
Constructor Injection: Dependencies are provided as constructor parameters. e.g. Pico container, Spring etc.
Setter Injection: Dependencies are assigned through JavaBeans properties (e.g.: setter methods).
Interface Injection: It is done through an interface. e.g. Avalon.
What is Spring OXM?
Spring OXM stands for Spring Object XML Mappers. It is a one of the Spring framework modules. This module is help to ease the mappings between java object and XML documents. The module can extend. Hence, it provides integration with various other popular frameworks such as JAXB, Castor, XStream etc.
What is Spring AOP?
Spring AOP stands for Aspect -oriented programming. It is one of the main components of spring framework. It complements OOP by providing another way of thinking program structure. It helps in breaking down the logic of the program into several distinct parts called as concerns. Cross-cutting concerns is the functions which span multiple points of an application.
What are some Spring AOP concepts?
- Aspect
- Join Point
- Advice
- Pointcut
- Introduction (For Interfaces)
- Target objects
- AOP Proxy
- Weaving
What is a AOP Proxy?
In AOP, A proxy is an object that is created after applying advice to a target object. when you think of client objects the target object and the proxy object are the same.
What are the AOP Proxy types?
There are three types of AOP proxies.
- BeanNameAutoProxyCreator: This is a BeanPostProcessor that creates AOP proxies for beans automatically by matching names.
- DefaultAdvisorAutoProxyCreator: This also applies eligible advisors automatically to bean in the current context.Â
- Metadata Autoproxying: It can be performed inspiring which can be driven by metadata. This is determined by source level attributes and keeps metadata inside the source code.
What is Waving in Spring?
It is process of linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime
What do the proxy-target-class attributes do in Spring AOP?
To force the use of CGLIB proxies set the value of the proxy-target-class attribute of the element to true.
<aop:config proxy-target-class="true">
   <!-- other beans defined here... -->
</aop:config>
Can you explain, how can JDBC be used more efficiently in the Spring framework?
When using the Spring JDBC framework the burden of resource management and error handling is reduced. So, developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a template class provided by Spring framework, called JdbcTemplate.
What is Spring JDBC Template?
Spring JDBC Template is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of JDBC API.
What are the most used design patterns in Spring?
- IOC
- Singleton Pattern
- Factory Pattern
- Prototype Pattern
- Proxy Pattern
- MVC Pattern
- Template Method Pattern
- Front controller design pattern
- Prototype Pattern
- Adapter Pattern
- Data Access object
- View Helper
What are the Problems of JDBC API in Spring JDBC?
 The problems of JDBC API are as follows:
- Â To write a lot of code before and after executing the query, such as creating connection, statement, closing result set, connection etc.
- To perform exception handling code on the database logic.
- Â To handle transaction.
- Repetition of all these codes from one to another database logic is a time consuming task.
Can you explain Bean lifecycle in Spring framework?
The spring container finds the bean’s definition from the XML file and instantiates the bean.
- Spring populates all of the properties as specified in the bean definition (DI).
- If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
- If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
- If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
- If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has init methoddeclaration, the specified initialization method is called.
- If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methodswill be called.
- If the bean implements DisposableBean, it will call the destroy() method
What is use of @Qualifier annotation?
In Spring,When there are more than one beans of the same type and only one is needed to be wired with a property, the @Qualifierannotation is used along with @Autowired annotation to remove the confusion by specifying which exact bean will be wired.
What are the mono and flux types?
The WebFlux framework in Spring Framework 5 uses Reactor as its async foundation.It is provides two core types: Mono to represent a single async value, and Flux to represent a stream of async values. They both implement the Publisher interface defined in the Reactive Streams specification.
Mono implements Publisher and returns 0 or 1 elements:
public abstract class Mono<T> implements Publisher<T> {...}
Also, Flux implements Publisher and returns N elements:
public abstract class Flux<T> implements Publisher<T> {...}
By definition, the two types represent streams, hence they’re both lazy, which means nothing is executed until we consume the stream using the subscribe () method. Both types are immutable, therefore calling any method will return a new instance of Flux or Mono.
What are some popular Spring annotations that you use in your project?
Spring has many Annotations to serve different purposes. For regular use we refer following popular Spring annotations:
@Controller
@Configuration
@RequestMapping
@ResponseBody
@PathVariable
@Autowired
@Service
@Scope
@Aspect
@Before
@After
@Around
@Joinpoint
@Pointcut