Thursday, July 24, 2014

Spring and Inversion of Control

(Credit goes to all my colleagues who spared their precious time to make this collection through various sources)


There is a lot of confusion about the definition of the IoC container – some equate it with a design pattern called Dependency Injection – but in reality IoC is much larger than dependency injection. The Spring IoC container enforces dependency injection in its various forms and employs a number of established design patterns to achieve this.
The main idea behind Inversion of Control as a concept is that component dependencies, lifecycle events, and configuration reside outside of the components themselves, and in the case of Spring, in the framework. This may sound a bit like giving up too much control, but in fact it can make your code more manageable, more testable, and more portable.
It's important to understand on the most basic level what the dependency injection pattern is and how it emerged in object oriented programming methodology. Spring's Inversion of Control framework is based on some best practice patterns – aspects of Spring IoC resemble and include the Factory and Observer patterns, and its most prominent feature is its implementation of a framework which enforces use of the dependency injection pattern.

1.      Dependency Inversion: Precursor to Dependency Injection

The first reference to what would eventually become Dependency Injection appeared in 1994 in a paper by Robert C. Martin called “The Dependency Inversion Principle”.
In “The Dependency Inversion Principle” (or DIP), the author states the three defining factors of “bad code”:
  1. It is hard to change because every change affects too many other parts of the system (Rigidity)
  2. When you make a change, unexpected parts of the system break (Fragility)
  3. It is hard to reuse in another application because it cannot be disentangled from the current application (Immobility) [3]
According to Martin, interdependency causes these coding problems (we'll call them RFI for Rigidity, Fragility, and Immobility). To fix RFI issues in your OO code, DIP has two basic rules:
1. High level modules should not depend upon low level modules, both should depend upon abstractions.
In other words, high level modules – which contain your business logic and all of the important meat of your application – should not depend on lower level components. The reason for this is if these lower level components were to change, the changes might affect the higher level components as well. This is the defining concept behind dependency inversion, that the prevailing wisdom of having higher-level modules dependent on lower-level modules is in fact a bad idea.
2. Abstractions should not depend upon details, details should depend upon abstractions.
This is another way to say that before you begin coding to the abstraction – the interface or abstract class -- you should find the common behaviors in the code and work backwards. Your interface /abstraction should cater to the intersection between the needs of your business logic and the common behaviors of the lower level modules. You should also leave the details of how these behaviors are implemented to the implementation classes.

However, there is one problem with this implementation. We definitely need one main method in order to run our application, and somewhere in this main method we will need to instantiate the low level module.By instantiating the low level module in our main method, we would break Rule #1 of Dependency Inversion. We have coded to the abstraction, we have integrated our changes, but our application would still have a dependency on a lower level class.

2.      Dependency Injection To The Rescue

Dependency Injection takes the level of decoupling that began with the Dependency Inversion Principle one step further. Dependency injection has the concept of an assembler – or what in Java is commonly referred to as a Factory -- that instantiates the objects required by an application and “injects” them into their dependent objects.
In the case of a dependency injection-informed framework such as Spring, components are coded to interfaces, just as in the DIP example above. But now the IoC container manages the instantiation, management, and class casting of the implemented objects so that the application doesn't have to. This removes any true dependencies on low-level implemented classes.
There are three types of Dependency Injection employed by IoC container providers.
Table 1. Dependency Injection Types
DI Type
Description
Constructor Injection
The constructor arguments are injected during instance instantiation.
Setter Injection
This is the most favored method of dependency injection in Spring. Dependencies are “set” in the objects through setter methods defined in a Spring configuration file.
Interface Injection
This is not implemented in Spring currently, but by Avalon. It’s a different type of DI that involves mapping items to inject to specific interfaces.

Spring uses the concept of a BeanFactory as its assembler, and it is the BeanFactory that manages the JavaBeans you have configured to run within it. In the next section we will discuss Spring's IoC container and how it makes use of dependency injection patterns to make your code, well, RFI-free, and just better.

3.      Bean management through IoC

Through its factory, Spring's IoC container manages the objects that it is configured to instantiate. Spring's management of the container objects adds flexibility and control to your application, and provides a central place of configuration management for your Plain Old Java Objects.
For example, through Spring IoC you can configure the number of instances of the component – whether the component is a singleton or not – and at what point the component is created and destroyed in memory. In Spring, the initialization of a bean by the framework is exactly equivalent to using the new keyword to instantiate an object in Java code. Once the framework has instantiated the object, it manages the scope of the bean, based on its configuration.
Because the IoC container is managing the beans, JNDI lookups that are typical in Java EE containers are no longer required, leaving your code container-agnostic and easier to unit test both inside and outside of the framework. And while you are coding to interfaces as part of good OO practice, Spring allows you to manage what implementations are used by leveraging dependency injection, resulting in cleaner, decoupled components.

The IoC container can also be configured to receive instantiation and destruction callback events for a particular bean. Certain components such as a database connection pool obviously need to be initialized and destroyed when the application is shutdown. Instead of using your custom code, Spring can manage these lifecycle events.
===================================================================
What is Spring Framework?
The Spring Framework is an open source application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.

What is new in Spring 2.5 as compared to 2.0?
The newly released Spring 2.5 continues this trend by offering further simplifications and powerful new features especially for those who are using Java 5 or greater. These features include annotation-driven dependency injection, auto-detection of Spring components on the classpath using annotations rather than XML for metadata, annotation support for lifecycle methods, a new web controller model for mapping requests to annotated methods, support for Junit 4 in the test framework, new additions to the Spring XML namespaces, and more.

What are the benefits of using Spring Tool Suite?
SpringSource Tool Suite (STS) is an Eclipse-based IDE with pre-installed plugins that provides valuable features for Spring developers. In addition to support for the core Spring framework, STS also provides visual editors, project validators, and Spring Dashboard for other projects such as Spring Roo, Grails, Groovy, Gradle, tcServer, and Spring Insight
The main plugin for STS is Spring IDE, which provides the fundamental Spring tooling features. STS comes preconfigured with many other plugins such as M2Eclipse for Maven, Web Tools Platform (WTP), Data Tools Platform (DTP), and AspectJ Development Tools (AJDT) and JUnit tooling.

What are the features of the new spring build system in use now days?
We are now using a new Spring build system as known from Spring Web Flow 2.0. This gives us:
1.       Ivy-based "Spring Build" system
2.       consistent deployment procedure
3.       consistent dependency management
4.       consistent generation of OSGi manifests
===================================================================
1. What does a simple spring application contain?
Ans. These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to configure the classes, known as theSpring configuration file.

Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

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.
2. What are the Core container module and Application context module?
Core container module provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.
Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.

3. What is a BeanFactory and XMLBeanFactory?
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.

XmlBeanFactory: BeanFactory has many implementations in Spring. But one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.

4. What is layered architecture in spring?
Ans. Spring is one-stop shop for all your enterprise applications, however, Spring is modular, layered, allowing you to pick and choose which modules are applicable to you, without having to bring in the rest. 
The Spring Framework provides about 20 modules which can be used based on an application requirement. 
Following section gives detail about all the modules available in Spring Framework.

Core Container:
The Core Container consists of the Core, Beans, Context, and Expression Language modules whose detail is as follows:

The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features.

The Bean module provides BeanFactory which is a sophisticated implementation of the factory pattern.

The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module.

The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime.

Data Access/Integration:
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules whose detail is as follows:

The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding.

The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.

The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.

The Java Messaging Service JMS module contains features for producing and consuming messages.

The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs.

Web:
The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules whose detail is as follows:

The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.

The Web-Servlet module contains Spring\'s model-view-controller (MVC) implementation for 
web applications.

The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring application.

The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.

Miscellaneous:
There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules whose detail is as follows:

The AOP module provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.

The Aspects module provides integration with AspectJ which is again a powerful and 
mature aspect oriented programming (AOP) framework.
The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers.

The Test module supports the testing of Spring components with JUnit or TestNG frameworks.

5. What are the advantages of Spring Framework?
Ans. The advantages of spring are as follows:
1.    Spring has layered architecture. So it is up to the programmer what to use and what to leave.
2.  Spring Enables POJO (Plain old Java object) Programming. POJO programming enables continuous integration and testability.
3.     Dependency Injection and Inversion of Control Simplifies JDBC (Java Database Connectivity), open source and no vendor lock-in.

6. What are Spring beans
A: The objects that form the backbone of your 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 you supply to the container, for example, in the form of XML <bean/> definitions.

7. What does a bean definition contain
A: The bean definition contains the information called configuration metadata which is needed for the container to know the followings:
·         How to create a bean
·         Bean's lifecycle details
·         Bean's dependencies

8. What is Spring IoC container?
A: 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.

9. How is a typical spring implementation look like?
For a typical Spring Application we need the following files:
·         An interface that defines the functions.
·         An Implementation that contains properties, its setter and getter methods, functions etc.,
·         Spring AOP (Aspect Oriented Programming)
·         A XML file called spring configuration file.
·         Client program that uses the function.

        10. What is the typical Bean life cycle in Spring Bean Factory Container?
Bean life cycle in Spring Bean Factory Container is as follows:
·         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 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.
10.a. Explain Bean lifecycle in Spring framework
A: 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 postprocess 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 .

11. Describe some of the standard Spring events.
A. 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. You can poll your database or you 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. You 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.

12. What is Dependency Injection?
Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.
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.

Q: What do you understand by Dependency Injection?How do we implement DI in Spring Framework?
A: As the name implies Inversion of control means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it’s the responsibility of container to create object as required. We maintain one xml file where we configure our components, services, all the classes and their property. We just need to mention which service is needed by which component and container will create the object for us. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.Example:
<bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont">                     <property name="newBid"/>        </bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done automatically by Spring, refereed as auto-wiring of bean in Spring.

        The Dependency Inversion Principle states that:
·         High level modules should not depend upon low level modules. Both should depend upon abstractions.
·         Abstractions should not depend upon details. Details should depend upon abstractions.
 The Dependency Inversion principle (DIP) helps us to develop loosely couple code by ensuring that high-level modules depend on abstractions rather than concrete implementations of lower-level modules. The Inversion of Control pattern is an implementation of this principle

Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object (or client) and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior, which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles

Types of Dependency Injection

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

When to use Dependency Injections?
A: The main benefits of IOC or dependency injection are:
·        It minimizes the amount of code in your application.·        It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.·        Loose coupling is promoted with minimal effort and least intrusive mechanism.·        IOC containers support eager instantiation and lazy loading of services.

13. What are the benefits of IOC?
Reduce glue code.
Externalize dependencies.
Manage dependencies in a single place.
Improve testability.
Foster good application design
  
14Explain 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 postprocess 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

15. What is Annotation-based container configuration?
A: 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.

Q: How do you turn on annotation wiring?
A: Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.

Q: What does @Required annotation mean?
A: 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.

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

Q: What does @Qualifier annotation mean?
A: There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

Q: Use of @Resource

A: This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.

What are the JSR-250 Annotations? Explain them with respect to Spring.
JSR-250 aka Common Annotations for the Java Platform was introduced as part of Java EE 5 an is usually used to annotated EJB3s. What’s not so well known is that Spring has supported three of the annotations since version 2.5. The annotations supported are:

@PostContruct - This annotation is applied to a method to indicate that it should be invoked after all dependency injection is complete.
@PreDestroy - This is applied to a method to indicate that it should be invoked before the bean is removed from the Spring context, i.e. just before it’s destroyed.
@Resource - This duplicates the functionality of @Autowired combined with @Qualifier as you get the additional benefit of being able to name which bean you’re injecting, without the need for two annotations.

Q: What is Spring Java Based Configuration? Give some annotation example.
A: Java based configuration option enables you to write most of your 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.

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

Explain the @Controller annotation
In spring-context first we need to declare a bean. This is just a stand spring bean definition in dispatcher’s context.
Latest way of doing this is, enabling autodetection.
For the @Controller annotation spring gives a feature of autodetection. We can add “component-scan” in spring-context and provide the base-package.
<context:component-scan base-package="com.javapapers.spring.mvc" /> 
<mvc:annotation-driven />   
Then add @Controller annotation to controllers.
The dispatcher will start from the base-package and scan for beans that are annotated with @Controller annotation and look for @RequestMapping. @Controller annotation just tells the container that this bean is a designated controller class.

Explain @RequestMapping annotation
@RequestMapping annotation is used to map a particular HTTP request method (GET/POST) to a specific class/method in controller which will handle the respective request.
 @RequestMapping annotation can be applied both at class and method level. 
In class level we can map the URL of the request and in method we can map the url as well as HTTP request method (GET/POST).
We can use wildcard characters like * for path pattern matching.


1)       Explain the different modules in Spring framework?
Ans –
·         Spring Core Module
·         Spring Context [ J2EE ]
·         Spring DAO Module [ Spring JDBC ]
·         Spring ORM module
·         Spring AOP [ Aspect Oriented Programming ]
·         Spring WEB-MVC Module

1)       Difference Between @Component, @Service, @Repository and @Controller?
Ans- Major difference between these stereotypes is they are used for different classification.
In a multitier application, we will have different layers like presentation, service, business, data access etc. When a class is to be annotated for auto-detection by Spring, then we should use the respective stereotype as below.
@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.

1)       Name some of the design patterns used in Spring Framework?
Ans-
1. MVC - The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers.

2. Front controller - Spring provides "DispatcherServlet" to ensure an incoming request gets dispatched to your controllers.

3. View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.

4. Singleton - Beans defined in spring config files are singletons by default.

5. Prototype - Instance type can be prototype.

6. Factory - Used for loading beans through BeanFactory and Application context.

7. Builder - Spring provides programmatic means of constructing BeanDefinitions using the builder pattern through Class "BeanDefinitionBuilder".

8. Template - Used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate.

9. Proxy - Used in AOP & Remoting.

10. DI/IOC - It is central to the whole BeanFactory/ApplicationContext stuff.

1)       What are some of the best practices for Spring Framework?
·          DO NOT use version numbers with the Spring schema namespaces
·         Always use the classpath:/ prefix for consist-resource referencing
·         Always use a single XML config file to bootstrap the application or tests
·         Use the XML “id” attribute to identify a bean
·         Use Constructor injection to promote thread safety
·         Use Properties for configurable resources
·         DO NOT use the SysOutOverSLF4J for anything other than migration

16. How to create ApplicationContext in a Java Program? ORWhat are the common implementations of the ApplicationContext?

There are following ways to create spring context in a standalone java program.
  1. AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
  2. ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
  3. FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.


What is the difference between Bean Factory and ApplicationContext
Following are some of the differences:
·    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.
·         The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.


ApplicationContext.
BeanFactory
Here we can have more than one config files possible

In this only one config file or .xml file
Application contexts can publish events to beans that are registered as listeners
Doesn’t support.
Support internationalization (I18N) messages
Doesn’t support.
Support application life-cycle events, and validation
Doesn’t support.
Support  many enterprise services such JNDI access, EJB integration, remoting
Doesn’t support.

17. BeanFactory vs ApplicationContext in Spring

Before seeing difference between ApplicationContext and BeanFactory, let see some similarity between both of them. Spring provides two kinds of IOC container, one is BeanFactory and other is ApplicationContext. Syntactically BeanFactory and ApplicationContext both are Java interfaces and ApplicationContext extends BeanFactory. Both of them are configuration using XML configuration file. In short BeanFactory provides basic IOC and DI features while ApplicationContext provides advanced features. Apart from these, Here are few more difference between BeanFactory and ApplicationContext which is mostly based upon features supported by them.

1) BeanFactory doesn't provide support for internationalization i.e. i18n but ApplicationContext provides support for it.

2) Another difference between BeanFactory vs ApplicationContext is ability to publish event to beans that are registered as listener.

3) One of the popular implementation of BeanFactory interface is XMLBeanFactory while one of the popular implementation of ApplicationContext interface is ClassPathXmlApplicationContext. On Java web application we use WebApplicationContext  which extends ApplicationContext interface and adds getServletContext method.

4) If you are using auto wiring and using BeanFactory than you need to register AutoWiredBeanPostProcessor using API which you can configure in XML if you are using  ApplicationContext. In summary BeanFactory is OK for testing and non production use but ApplicationContext is more feature rich container implementation and should be favored over BeanFactory

These were some worth noting difference between BeanFactory and ApplicationContext in Spring framework. In most practical cases you will be using ApplicationContext but knowing about BeanFactory is important to understand fundamental concept of spring framework. I mostly use XML configuration file and ClassPathXmlApplicationContext to quickly run any Spring based Java program from Eclipse  by using following snippet of code :

public static void main(String args[]){
    ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
    Hello hello = (Hello) ctx.getBean("hello");
    hello.sayHello("John");
}

here beans.xml is your spring configuration file and “hello” is a bean defined in that spring configuration file. Here we have used ClassPathXmlApplicationContext  which is an implementation of ApplicationContext interface in Spring.

What is spring web module?
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.
The Spring framework is a layered architecture consisting of seven well-defined modules. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in the following figure.

Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:
* The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.
* Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
* Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
* Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.
* Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.
* Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
* Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.
Spring framework functionality can be used in any J2EE server and most of it also is adaptable to non-managed environments. A central focus of Spring is to allow for reusable business and data-access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (Web or EJB), standalone applications, test environments, and so on, without any hassle.

Q20.How to get ServletContext and ServletConfig object in a Spring Bean?

There are two ways to get Container specific objects in the spring bean.
  1. Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces, please read Spring Aware Interfaces
  2. Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.
@Autowired
ServletContext servletContext;
===============================================================
Q: What are spring beans?
Each "bean" element in spring bean configuration file defines a JavaBean. Typically the bean class is specified, along with JavaBean properties and/or constructor arguments.

Q: How to customize bean destruction/initialization  process ?
Spring has two callbacks- initialization and destruction.

1. Initialization: This interface org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work. This interface has a method afterPropertiesSet() which is invoked by container after bean initialization(after all properties are set).
2. Destruction: The org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. This interface has a method destroy() which is invoked by container before bean is destroyed.

It is recommended to avoid using the InitializingBean or DisposableBean callbacks, because XML configuration gives much more flexibility in terms of naming the method.
Q: In scenarios where you have to avoid using auto wiring, what are the other options that can be explored to achieve the same?
We can avoid using autowiring for simple primitive types(int,String,Enum) rather we can use simple xml property elements to set the dependencies

Q: Does Spring Bean provide thread safety?
The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe.
However we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.

Q: What are Bean scopes in Spring Framework ?
A: When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.
The default scope of bean is Singleton for Spring framework.
The Spring Framework supports following five scopes, three of which are available only if you use a web-aware Application Context.

Scope
Description
Singleton
This scopes the bean definition to a single instance per Spring IoC   container (default).
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 Application Context.
Session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware  Spring Application Context.
Global-session:
This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring Application Context

Q: How do you define a bean scope
A: When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.

Q: What is default scope of bean in Spring framework
A: The default scope of bean is Singleton for Spring framework.

Q: What are singleton beans and how can you create prototype beans?
Ans. Basically a bean has scopes which defines 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.

<bean id="createNewStock" class="springexample.
stockMarket.CreateNewStockAccont" singleton="false"> 
              <property name="newBid"/> 
</bean>

If you want to create only one instance per container then better to create a bean at singleton scope(like Connection Factory) where as If you want a bean per getBean() method call on the BeanFactory/ApplicationContext  go with prototype scope.
Q: What would happen if we have a prototype bean injected into a singleton bean ? How many objects of prototype bean object will be created ?
Ans : If prototype bean injected into a singleton bean ,a new prototype bean is instantiated and then dependency-injected into the singleton bean. One object will be created.

Q: What is Spring Java Based Configuration? Give some annotation example
Annotating a class with the @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. The simplest possible @Configuration class would be as follows:
package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {

   @Bean
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}                                                                                                                                                                                                                                        
Above code will be equivalent to the following XML configuration:

<beans>
   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld" />
</beans>                                                                                                                                                                                                                         
Client Program                                                                                                                                                                                      public static void main(String[] args) {
   ApplicationContext ctx =
   new AnnotationConfigApplicationContext(HelloWorldConfig.class);
  
   HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

   helloWorld.setMessage("Hello World!");
   helloWorld.getMessage();
}


Q: What is bean wiring?
Ans: Combining beans together within the Spring container is known as bean wiring. When wiring beans, the programmer should tell the container what beans are needed and how the container should use dependency injection to tie them together.


Q:  What is Auto wiring? What are different types of Autowire types?
A: 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 your bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.

Q: What are different Modes of auto wiring?
A: The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean definition.
·         no: This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.
·         byName: Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute 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.
·         byType: Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute 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.
·         constructor: 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.
·         autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

Q: What are the limitations with autowiring?
·         A: Limitations of autowiring are:
·         Overriding possibility: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
·         Primitive data types: You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
·         Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

Q: What are Inner Beans?
A: A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes.

Q: Explain the different types of AutoProxying.
·         BeanNameAutoProxyCreator 
·         DefaultAdvisorAutoProxyCreator 
·         Metadata autoproxying

Q: How do you use a particular implementation of collection in your bean definition ?
A: Spring offers four types of collection configuration elements which are as follows:
·         <list>: This helps in wiring i.e. injecting a list of values, allowing duplicates.
·         <set>: This helps in wiring a set of values but without any duplicates.
·         <map>: This can be used to inject a collection of name-value pairs where name and value can be of any type.
·         <props>: This can be used to inject a collection of name-value pairs where the name and value are both Strings.

Q: Are spring singleton beans thread safe
A: No, singleton beans are not thread-safe in Spring framework.

Q: What is Spring Expression Language
The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime.

Q: Can we have multiple Spring configuration files?
Ans: Yes

Q: Which DI would you suggest Constructor-based or setter-based DI
A: Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies.

Q: Give an example of BeanFactory implementation
A: The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.

Q: How do you provide configuration metadata to the Spring Container
A: There are following three important methods to provide configuration metadata to the Spring Container:
·         XML based configuration file.
·         Annotation-based configuration
·         Java-based configuration
Q: How to inject a java.util.Properties into a Spring Bean?
1.
<util:properties id="serverProperties" location="file:./applications/MyApplication/server.properties"/>
<util:properties id="someConfig" location="file:./applications/MyApplication/config.properties"/>

Grabbing in code:
@Autowired
@Qualifier("serverProperties")
private Properties serverProperties;
@Autowired
@Qualifier("someConfig")
private Properties otherProperties;
or

@Resource(name = "serverProperties")
private Properties serverProperties;
@Resource(name = "someConfig")
private Properties otherProperties;
2.
@Configuration
@PropertySource(name = "someName", value = {"classpath:a.properties", "classpath:b.properties"})
public class MyConfiguration {
}

3.
<context:property-override location="classpath:override.properties"/>
Properties file:
beanname1.foo=foovalue
beanname2.bar.baz=bazvalue
===============================================================
What is Spring DAO?
Ans - 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 one to switch between the aforementioned persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.

What are the types of the transaction management Spring supports ?
Ans - Spring Framework supports:
1. Programmatic transaction management.
2. Declarative transaction management

What are the benefits of the Spring Framework transaction management ?
Ans- The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
·         Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
·         Supports declarative transaction management.
·         Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
·         Integrates very well with Spring's various data access abstractions.

When to use programmatic and declarative transaction management ?
Ans - Programmatic transaction management is usually a good idea only if you have a small number of transactional operations.

On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.

What is JDBC abstraction and DAO module?
Ans – Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.

What are object/relational mapping integration module?
Ans - Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC

What kind of exceptions those spring DAO classes throw?
Ans- The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of DataAccessException

What is DataAccessException?
Ans - DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions

How to integrate Spring and Hibernate using HibernateDaoSupport?
Ans - This is a wrapper over HibernateTemplate. It can be initialized using a SessionFactory. It creates the HibernateTemplate and subclasses can use the getHibernateTemplate() method to obtain the hibernateTemplate and then perform operations on it. The class can also be initialized using a preconfigured HibernateTemplate. Create your own DAO by extending this class, provide a SessionFactory or HibernateTemplate and start performing operations using the getHibernateTemplate() method.

===========================================================
What is AOP
A: Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.

What is AOP module?
Ans. The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring's metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.

What is AOP Alliance?
Ans. AOP Alliance is an open-source project whose goal is to promote adoption of AOP and interoperability among different AOP implementations by defining a common set of interfaces and components.

What do you mean by Aspect ?
A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).
26. What is AOP? How it is used in Spring?
How the AOP used in Spring?
   AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework's transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP. 

What are the pros and cons between Spring AOP and AspectJ AOP?
A. 
The Spring AOP is simpler as it is achieved via a runtime dynamic proxy class. Unlike AspectJ, it does not have to go through load time weaving or a compiler. The Spring AOP uses the proxy and decorator design patterns.

Since Spring AOP uses proxy based AOP, it can only offer method execution pointcut, whereas the AspectJ  AOP supports all pointcuts.

In some cases, the compile time weaving (e.g. AspectJ AOP) offers better performance.


What is the difference between concern and cross-cutting concern in Spring AOP
A: Concern: Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns.
Cross-cutting concern: It's a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.

What is @AspectJ? based aspect implementation
A: @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

What is an Advice?
Ans.
 Advice is the implementation of an aspect, much like assigning application of a new behavior. Generally the advice is inserted into an application at jointpoints.
This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.

What are the different types of Advice?
A: Spring aspects can work with five kinds of advice mentioned below:
·         before: Run advice before the a method execution.
·         after: Run advice after the a method execution regardless of its outcome.
·         after-returning: Run advice after the a method execution only if method completes successfully.
·         after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
·         around: Run advice before and after the advised method is invoked.

What are Advice, Aspect, Join-point and point cut in spring?
Q: What is Join point?
A: This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.
Q: What is Pointcut?
A: This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.
Q: What is Introduction?
A: An introduction allows you to add new methods or attributes to existing classes.
Q: What is Target object?
A: The object being advised by one or more aspects, this object will always be a proxy object. Also referred to as the advised object.
Q: What is Weaving?
A: Weaving is the process of linking aspects with other application types or objects to create an advised object.
Q: What are the different points where weaving can be applied?

A: Weaving can be done at compile time, load time, or at runtime.
===========================================================
This is personal collection for me and my colleagues: my employer has nothing to do with it. 
===========================================================