Spring Questions


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 benefits of Spring Framework?
  1. Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
  2. Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.
  3. Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services.
  4. Container: Spring contains and manages the life cycle and configuration of application objects.
  5. MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.
  6. Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
  7. Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.

Which are the Spring framework modules?



Explain the Core Container (Application context) module
This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container.

What is Spring IoC container?
The Spring IoC is responsible for creating the objects, managing them (with dependency injection (DI)), wiring them together, and configuring them, as also managing their complete lifecycle.

What are the benefits of IOC?
IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive mechanism. IOC containers support eager instantiation and lazy loading of services.

What is Dependency Injection in Spring?
Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways. This concept says 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 (the IOC container) is then responsible for hooking it all up.

What are the different types of IoC (dependency injection)?
  1. Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  2. Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Differentiate between constructor injection and setter injection.
Constructor Injection
Setter 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.

Which DI would you suggest Constructor-based or setter-based DI?
You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.

What are types of IoC containers? Explain them.
There are two types of IoC containers −
  • Bean Factory container − This is the simplest container providing basic support for DI. The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
  • Spring ApplicationContext Container − This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.

What are Spring beans?
Spring beans scope interview questions - The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed by the Spring IoC container. By default beans are singleton, we can define by using @Scope annotation.

Explain the bean scopes supported by Spring
There are five scoped provided by the Spring Framework supports following five scopes:
  1. In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container.
  2. In prototype scope, a single bean definition has any number of object instances.
  3. In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext.
  4. In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext.
  5. In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.
The default scope of a Spring Bean is Singleton.

Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.
Thread Safe Singleton: A thread safe singleton in created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread-safe, getInstance() method is made synchronized so that multiple threads can’t access it simultaneously.
// Java program to create Thread Safe 
// Singleton class 
public class ABC  
// private instance, so that it can be 
// accessed by only by getInstance() method 
private static ABC instance;   
private ABC()  
// private constructor 
  
//synchronized method to control simultaneous access 
  synchronized public static ABC getInstance()  
if (instance == null)  
// if instance is null, initialize 
instance = new ABC(); 
return instance; 


How do you provide configuration metadata to the Spring Container?
There are three important methods to provide configuration metadata to the Spring Container:
  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration

What are the common implementations of the ApplicationContext?
The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor.
The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.

What is the difference between Bean Factory and ApplicationContext?
Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, 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. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.

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

Explain different modes of auto wiring?
The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:
  1. no: This is default setting. Explicit bean reference should be used for wiring.
  2. byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowireattribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
  3. byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowireattribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
  4. constructor:This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
  5. autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire bybyType.
@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, on the constructor, on a property or on 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.

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, which is the JdbcTemplate

Spring DAO support
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows us to switch between the persistence technologies fairly easily and to code without worrying about catching exceptions that are specific to each technology.

What are the ways to access Hibernate by using Spring?
There are two ways to access Hibernate with Spring:
  1. Inversion of Control with a HibernateTemplate and Callback.
  2. Extending HibernateDAOSupport and Applying an AOP Interceptor node.

How can we integrate Spring and Hibernate using HibernateDaoSupport?
Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps:
  1. Configure the Hibernate SessionFactory
  2. Extend a DAO Implementation from HibernateDaoSupport
  3. Wire in Transaction Support with AOP

Types of the transaction management Spring support
Spring supports two types of transaction management:
  1. Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
  2. Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
We use annotate a method with @Transactional annotation for Declarative transaction management. 

Which Transaction management type is more preferable?
Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

Name the exceptions thrown by the Spring DAO classes.
See the below diagram, it depicts all the Spring DAO classes in the hierarchical order.



What do you understand by Aspect Oriented Programming?
Enterprise applications have some common cross-cutting concerns that are applicable to different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that are not possible in normal object-oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data.

What are the different AOP implementations?
Different AOP implementations are depicted by the below diagram:



What is 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.
Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join point is always the execution of a method.
Pointcut: Pointcut’s are regular expressions that are 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.
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 AOP Advice Types?
Based on the execution strategy of advices, they are of following types.
  1. Before Advice: These advices runs before the execution of join point methods. We can use @Before annotation to mark an advice type as Before advice.
  2. After (finally) Advice: An advice that gets executed after the join point method finishes executing, whether normally or by throwing an exception. We can create after advice using @After annotation.
  3. After Returning Advice: Sometimes we want advice methods to execute only if the join point method executes normally. We can use @AfterReturning annotation to mark a method as after returning advice.
  4. After Throwing Advice: This advice gets executed only when join point method throws exception, we can use it to rollback the transaction declaratively. We use @AfterThrowing annotation for this type of advice.
  5. Around Advice: This advice surrounds the join point method and we can also choose whether to execute the join point method or not. We can write advice code that gets executed before and after the execution of the join point method. It is the responsibility of around advice to invoke the join point method and return values if the method is returning something. We use @Around annotation to create around advice methods.

What is target object?
Target Object is a proxy object that is advised by one or more aspects.

What is weaving?
Weaving is a process of linking aspect with other application.

What is a Controller in Spring MVC?
Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.
A Controller class is responsible to handle a different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually, it’s used with @RequestMapping annotation to define handler methods for specific URI mapping.

What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?
@Component is used to indicate that a class is a component. These classes are used for auto-detection and configured as bean when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
@Service is used to indicate that a class is a Service. Usually, the business facade classes that provide some services are annotated with this.

What is DispatcherServlet and ContextLoaderListener?
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.

What is ViewResolver in Spring?
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file.

Describe DispatcherServlet?
The DispatcherServlet is the core of Spring Web MVC framework. It handles all the HTTP requests and responses. The DispatcherServlet receives the entry of handler mapping from the configuration file and forwards the request to the controller. The controller then returns an object of Model And View. The DispatcherServlet checks the entry of view resolver in the configuration file and calls the specified view component.
  
What are the minimum configurations needed to create Spring MVC application?
For creating a simple Spring MVC application, we would need to do the following tasks.
  • Add spring-context and spring-webmvc dependencies in the project.
  • Configure DispatcherServlet in the web.xml file to handle requests through spring container.
  • Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
  • Controller class with request mappings defined to handle the client requests.

How would you relate Spring MVC Framework to MVC architecture?
As the name suggests Spring MVC is built on top of Model-View-Controller architecture. DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller handler methods.
The model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages.
View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.

What are some of the important Spring annotations you have used?
Some of the Spring annotations that I have used in my project are:
  • @Controller – for controller classes in Spring MVC project.
  • @RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
  • @ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
  • @PathVariable – for mapping dynamic values from the URI to handler method arguments.
  • @Autowired – for autowiring dependencies in spring beans.
  • @Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
  • @Service – for service classes.
  • @Scope – for configuring scope of the spring bean.
  • @Configuration@ComponentScan and @Bean – for java based configurations.
  • AspectJ annotations for configuring aspects and advices, @Aspect@Before@After@Around@Pointcut etc.

How to upload file in Spring MVC Application?
Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write controller handler method to handle the incoming file and process it.

What is Spring MVC Interceptor and how to use it?
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandlepostHandle and afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.
Name some of the design patterns used in Spring Framework?
Spring Framework is using a lot of design patterns, some of the common ones are:
  1. Singleton Pattern: Creating beans with default scope.
  1. Factory Pattern: Bean Factory classes
  2. Prototype Pattern: Bean scopes
  3. Adapter Pattern: Spring Web and Spring MVC
  4. Proxy Pattern: Spring Aspect Oriented Programming support
  5. Template Method Pattern: JdbcTemplate, HibernateTemplate etc
  6. Front Controller: Spring MVC DispatcherServlet
  7. Data Access Object: Spring DAO support
  8. Dependency Injection and Aspect Oriented Programming

Explain Bean lifecycle in Spring framework?

Following is sequence of a bean lifecycle in Spring:
  1. Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.
  2. Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.
  3. Set Bean Name: If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
  4. Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
  5. Pre Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
  6. 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.
  7. Post Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  8. Ready to use: Now the bean is ready to use by the application
  9. Destroy: If the bean implements DisposableBean , it will call the destroy() method

What are inner beans in Spring?
In Spring framework, whenever a bean is used for only one particular property, it’s advise to declare it as an inner bean. And the inner bean is supported both in setter injection ‘property‘ and constructor injection ‘constructor-arg‘.
For example, let’s say we one Customer class having reference of Person class. In our application, we will be creating only one instance of Personclass, and use it inside Customer.
public class Customer
{
    private Person person;
    //Setters and Getters
}
public class Person
{
    private String name;
    private String address;
    private int age;
     
    //Setters and Getters
}

How is event handling done in Spring?
Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.

What are the different types of events in spring framework?
Spring’s ApplicationContext provides the functionality to support events and listeners in code. We can create beans that listen for events which are published through our ApplicationContext. Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.
public class AllApplicationEventListener implements ApplicationListener < ApplicationEvent >
{
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent)
    {
        //process event
    }
}
Spring provides the following 5 standard events:
  1. 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.
  2. ContextStartedEvent : This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving this event.
  3. ContextStoppedEvent : This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required house keeping work after receiving this event.
  4. 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.
  5. RequestHandledEvent : This is a web-specific event telling all beans that an HTTP request has been serviced.
Apart from above, you can create your own custom events by extending ApplicationEvent class. e.g.
public class CustomApplicationEvent extends ApplicationEvent
{
    public CustomApplicationEvent ( Object source, final String msg )
    {
        super(source);
        System.out.println("Created a Custom event");
    }
}
  

To listen this event, create a listener like this:
public class CustomEventListener implements ApplicationListener < CustomApplicationEvent >
{
    @Override
    public void onApplicationEvent(CustomApplicationEvent applicationEvent) {
        //handle event
    }
}

And to publish this event, you will need the help of applicationContext instance.
CustomApplicationEvent customEvent = new CustomApplicationEvent( applicationContext, "Test message" );
applicationContext.publishEvent ( customEvent );

How can you fetch records by spring JdbcTemplate?
You can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:
  1. ResultSetExtractor
  2. RowMapper

What is Spring Security?
Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.
To use Spring Security in web applications, you can get started with a simple annotation: @EnableWebSecurity.

No comments:

Post a Comment