UNIT-I
1) What is Spring Framework
  Introduction to Spring Framework
  Prior to the advent of Enterprise Java Beans (EJB), Java developers
  needed to use JavaBeans to create Web applications. Although
  JavaBeans helped in the development of user interface (UI)
  components, they were not able to provide services, such as transaction
  management and security, which were required for developing robust
  and secure enterprise applications. The advent of EJB was seen as a
  solution to this problem EJB extends the Java components, such as
  Web and enterprise components, and provides services that help in
  enterprise application development. However, developing an enterprise
  application with EJB was not easy, as the developer needed to perform
  various tasks, such as creating Home and Remote interfaces and
  implementing lifecycle callback methods which lead to the complexity of
  providing code for EJBs Due to this complication, developers started
  looking for an easier way to develop enterprise applications.
  The Spring framework(which is commonly known as Spring) has
  emerged as a solution to all these complications This framework uses
  various new techniques such as Aspect-Oriented Programming (AOP),
  Plain Old Java Object (POJO), and dependency injection (DI), to develop
  enterprise applications, thereby removing the complexities involved
    while developing enterprise applications using EJB, Spring is an open
    source lightweight framework that allows Java EE 7 developers to build
    simple, reliable, and scalable enterprise applications. This framework
    mainly focuses on providing various ways to help you manage your
    business objects. It made the development of Web applications much
    easier as compared to classic Java frameworks and Application
    Programming Interfaces (APIs), such as Java database
    connectivity(JDBC), JavaServer Pages(JSP), and Java Servlet.
    The Spring framework can be considered as a collection of sub-
    frameworks, also called layers, such as Spring AOP. Spring Object-
    Relational Mapping (Spring ORM). Spring Web Flow, and Spring Web
    MVC. It is a lightweight application framework used for developing
    enterprise applications. You can use any of these modules separately
    while constructing a Web application. The modules may also be grouped
    together to provide better functionalities in a Web application. Spring
    framework is loosely coupled because of dependency Injection.
    Features of the Spring Framework
    The features of the Spring framework such as IoC, AOP, and transaction
    management, make it unique among the list of frameworks. Some of the
    most important features of the Spring framework are as follows:
   IoC container:
    Refers to the core container that uses the DI or IoC pattern to implicitly
    provide an object reference in a class during runtime. This pattern acts
    as an alternative to the service locator pattern. The IoC container
    contains assembler code that handles the configuration management of
    application objects.
    The Spring framework provides two packages, namely
    org.springframework.beans and org.springframework.context which
    helps in providing the functionality of the IoC container.
   Data access framework:
    Allows the developers to use persistence APIs, such as JDBC and
    Hibernate, for storing persistence data in database. It helps in solving
    various problems of the developer, such as how to interact with a
    database connection, how to make sure that the connection is closed,
    how to deal with exceptions, and how to implement transaction
    management It also enables the developers to easily write code to
    access the persistence data throughout the application.
   Spring MVC framework:
    Allows you to build Web applications based on MVC architecture. All the
    requests made by a user first go through the controller and are then
    dispatched to different views, that is, to different JSP pages or Servlets.
    The form handling and form validating features of the Spring MVC
    framework can be easily integrated with all popular view technologies
    such as ISP, Jasper Report, FreeMarker, and Velocity.
   Transaction management:
    Helps in handling transaction management of an application without
    affecting its code. This framework provides Java Transaction API (JTA)
    for global transactions managed by an application server and local
    transactions managed by using the JDBC Hibernate, Java Data Objects
    (JDO), or other data access APIs. It enables the developer to model a
    wide range of transactions on the basis of Spring’s declarative and
    programmatic transaction management.
   Spring Web Service:
    Generates Web service endpoints and definitions based on Java
    classes, but it is difficult to manage them in an application. To solve this
    problem, Spring Web Service provides layered-based approaches that
    are separately managed by Extensible Markup Language (XML) parsing
    (the technique of reading and manipulating XML). Spring provides
    effective mapping for transmitting incoming XML message request to an
    object and the developer to easily distribute XML message (object)
    between two machines.
   JDBC abstraction layer:
    Helps the users in handling errors in an easy and efficient manner. The
    JDBC programming code can be reduced when this abstraction layer is
    implemented in a Web application. This layer handles exceptions such
    as DriverNotFound. All SQLExceptions are translated into the
    DataAccessException class. Spring’s data access exception is not JDBC
    specific and hence Data Access Objects (DAO) are not bound to JDBC
    only.
   Spring TestContext framework:
    Provides facilities of unit and integration testing for the Spring
    applications. Moreover, the Spring TestContext framework provides
    specific integration testing functionalities such as context management
    and caching DI of test fixtures, and transactional test management with
    default rollback semantics.
    Evolution of Spring Framework
    The framework was first released under the Apache 2.0 license in June
    2003. After that there has been a significant major revision, such as
    Spring 2.0 provided XML namespaces and AspectJ support, Spring 2.5
    provide annotation-driven configuration, Spring 3.0 provided a Java-
    based @Configuration model. The latest release of the spring framework
    is 4.0. it is released with the support for Java 8 and Java EE 7
    technologies. Though you can still use Spring with an older version of
    java, the minimum requirement is restricted to Java SE 6. Spring 4.0 also
     supports Java EE 7 technologies, such as java message service (JMS)
     2.0, java persistence API (JPA) 2.1, Bean validation 1.1, servlet 3.1, and
     JCache.
  2) Spring Framework – Modules
Spring Framework Architecture
    The Spring framework consists of seven modules which are shown in the
    above Figure. These modules are Spring Core, Spring AOP, Spring Web
    MVC, Spring DAO, Spring ORM, Spring context, and Spring Web flow.
    These modules provide different platforms to develop different
    enterprise applications; for example, you can use Spring Web MVC
    module for developing MVC-based applications.
    Spring Framework Modules
   Spring Core Module:
    The Spring Core module, which is the core component of the Spring
    framework, provides the IoC container There are two types of
    implementations of the Spring container, namely, bean factory and
    application context. Bean factory is defined using the
    org.springframework.beans.factory.BeanFactory interface and acts as a
    container for beans. The Bean factory container allows you to decouple
    the configuration and specification of dependencies from program logic.
    In the Spring framework, the Bean factory acts as a central IoC container
    that is responsible for instantiating application objects. It also configures
    and assembles the dependencies between these objects. There are
    numerous implementations of the BeanFactory interface. The
    XmlBeanFactory class is the most common implementation of the
    BeanFactory interface. This allows you to express the object to compose
    your application and remove interdependencies between application
    objects.
   Spring AOP Module:
    Similar to Object-Oriented Programming (OOP), which breaks down the
    applications into hierarchy of objects, AOP breaks down the programs
    into aspects or concerns. Spring AOP module allows you to implement
    concerns or aspects in a Spring application in Spring AOP, the aspects are
    the regular Spring beans or regular classes annotated with @Aspect
    annotation. These aspects help in transaction management and logging
    and failure monitoring of an application. For example, transaction
    management is required in bank operations such as transferring an
    amount from one account to another Spring AOP module provides a
    transaction management abstraction layer that can be applied to
    transaction APIs.
   Spring ORM Module:
    The Spring ORM module is used for accessing data from databases in an
    application. It provides APIs for manipulating databases with JDO,
    Hibernate, and iBatis. Spring ORM supports DAO, which provides a
    convenient way to build the following DAOs-based ORM solutions:
       o Simple declarative transaction management
       o Transparent exception handling
       o Thread-safe, lightweight template classes
       o DAO support classes
       o Resource management
   Spring Web MVC Module:
    The Web MVC module of Spring implements the MVC architecture for
    creating Web applications. It separates the code of model and view
    components of a Web application. In Spring MVC, when a request is
    generated from the browser, it first goes to the DispatcherServlet class
    (Front Controller), which dispatches the request to a controller
    (SimpleFormController class or AbstractWizardformController class)
    using a set of handler mappings. The controller extracts and processes
    the information embedded in a request and sends the result to the
    DispatcherServlet class in the form of the model object. Finally, the
    DispatcherServlet class uses ViewResolver classes to send the results to a
    view, which displays these results to the users.
   Spring Web Flow Module:
    The Spring Web Flow module is an extension of the Spring Web MVC
    module. Spring Web MVC framework provides form controllers, such as
    class SimpleFormController and AbstractWizardFormController class, to
    implement predefined workflow. The Spring Web Flow helps in defining
    XML file or Java Class that manages the workflow between different
    pages of a Web application. The Spring Web Flow is distributed
    separately and can be downloaded
    through http://www.springframework.org website.
    The following are the advantages of Spring Web Flow:
       o The flow between different UIs of the application is clearly
           provided by defining Web flow in XML file.
       o Web flow definitions help you to virtually split an application in
           different modules and reuse these modules in multiple situations.
   Spring Web DAO Module:
    The DAO package in the Spring framework provides DAO support by
    using data access technologies such as JDBC, Hibernate, or JDO. This
    module introduces a JDBC abstraction layer by eliminating the need for
    providing tedious JDBC coding. It also provides programmatic as well as
    declarative transaction management classes. Spring DAO package
    supports heterogeneous Java Database Connectivity and O/R mapping,
    which helps Spring work with several data access technologies. For easy
    and quick access to database resources, the Spring framework provides
    abstract DAO base classes. Multiple implementations are available for
    each data access technology supported by the Spring framework. For
    example, in JDBC, the JdbcDaoSupport class and its methods are used to
    access the DataSource instance and a preconfigured JdbcTemplate
    instance. You need to simply extend the JdbcDaoSupport class and
    provide a mapping to the actual DataSource instance in an application
    context configuration to access a DAO-based application.
   Spring Application Context Module:
    The Spring Application context module is based on the Core module.
    Application context org.springframework.context.ApplicationContext is
    an interface of BeanFactory. This module derives its feature from the
   org.springframework.beans package and also supports functionalities
   such as internationalization (I18N), validation, event propagation, and
   resource loading. The Application context implements MessageSource
   interface and provides the messaging functionality to an application.
   How to download and install Spring framework
1. For Downloading Spring Repository you need to
   visit https://repo.spring.io/release/org/springframework/spring/. In this
   website, you will find different spring framework releases. You have to
   click on latest framework release. Here you will find three files which are:
        spring-framework-5.1.4.RELEASE-dist.zip
        spring-framework-5.1.4.RELEASE-docs.zip
        spring-framework-5.1.4.RELEASE-schema.zip
2. For Installing, You need to extract the “spring-framework-5.1.4.RELEASE-
   dist.zip” file in your C drive. Now you are able to run your application in
   spring framework.
   Want to be a master in Backend Development with Java for building
   robust and scalable applications? Enroll in Java Backend and
   Development Live Course by GeeksforGeeks to get your hands dirty with
   Backend Programming. Master the key Java concepts, server-side
   programming, database integration, and more through hands-on
   experiences and live projects. Are you new to Backend development or
   want to be a Java Pro? This course equips you with all you need for
   building high-performance, heavy-loaded backend systems in Java.
   Ready to take your Java Backend skills to the next level? Enroll now and
   take your development career to sky highs.
  3) Configuring IoC container using Java-based configuration
Spring - Java-based Container Configuration
     Basic Concepts: @Bean and @Configuration
     The central artifacts in Spring’s new Java-configuration support
     are @Configuration-annotated classes and @Bean-annotated methods.
     The @Bean annotation is used to indicate that a method instantiates,
     configures, and initializes a new object to be managed by the Spring IoC
     container. For those familiar with Spring’s XML configuration,
     the @Bean annotation plays the same role as the element. You can
     use @Bean-annotated methods with any Spring @Component. However,
     they are most often used with @Configuration beans.
     Annotating a class with @Configuration indicates that its primary
     purpose is as a source of bean definitions.
     Furthermore, @Configuration classes let inter-bean dependencies be
     defined by calling other @Bean methods in the same class. The simplest
     possible @Configuration class reads as follows:
     The below simple example show usage
     of @Bean and @Configuration annotations.
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;
  import com.companyname.projectname.customer.CustomerService;
  import com.companyname.projectname.order.OrderService;
  @Configuration
  public class Application {
      @Bean
      public CustomerService customerService() {
        return new CustomerService();
      }
      @Bean
      public OrderService orderService() {
        return new OrderService();
      }
  }
  The preceding configuration is exactly equivalent to the following Spring
  XML:
  <beans>
       <bean id="customerService"
  class="com.companyname.projectname.CustomerService"/>
       <bean id="orderService"
  class="com.companyname.projectname.OrderService"/>
  </beans>
  Note that the method name and bean name in XML are exactly the
  same.
4) Introduction To Dependency Injection
Spring Dependency Injection with Example
     Dependency Injection is the main functionality provided
     by Spring IOC(Inversion of Control). The Spring-Core module is
     responsible for injecting dependencies through either Constructor or
     Setter methods. The design principle of Inversion of Control emphasizes
     keeping the Java classes independent of each other and the container
     frees them from object creation and maintenance. These classes,
     managed by Spring, must adhere to the standard definition of Java-Bean.
     Dependency Injection in Spring also ensures loose coupling between the
     classes.
     For developers aiming to master this critical aspect of Spring and
     implement it effectively in real-world applications, exploring a
     dedicated Java backend development course can offer in-depth
     knowledge and practical experience, enabling you to build modular,
     maintainable, and scalable applications with ease.
      Need for Dependency Injection:
      Suppose class One needs the object of class Two to instantiate or
      operate a method, then class One is said to be dependent on class Two.
      Now though it might appear okay to depend on a module on the other,
      in the real world, this could lead to a lot of problems, including system
      failure. Hence such dependencies need to be avoided. Spring IOC
      resolves such dependencies with Dependency Injection, which makes
      the code easier to test and reuse .
      Loose coupling between classes can be possible by defining interfaces for
      common functionality and the injector will instantiate the objects of
required implementation. The task of instantiating objects is done by the
container according to the configurations specified by the developer.
Types of Spring Dependency Injection
There are two primary types of Spring Dependency Injection:
1. Setter Dependency Injection (SDI):
Setter DI involves injecting dependencies via setter methods. To
configure SDI, the @Autowired annotation is used along with setter
methods, and the property is set through the <property> tag in the bean
configuration file.
Bean Configuration:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <bean id="GFG" class="com.geeksforgeeks.org.GFG">
    <property name="geek">
      <ref bean="CsvGFG" />
    </property>
  </bean>
<bean id="CsvGFG" class="com.geeksforgeeks.org.impl.CsvGFG" />
<bean id="JsonGFG" class="com.geeksforgeeks.org.impl.JsonGFG" />
</beans>
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.IGeek;
import org.springframework.beans.factory.annotation.Autowired;
public class GFG {
  // The object of the interface IGeek
  private IGeek geek;
    // Setter method for property geek with @Autowired annotation
    @Autowired
    public void setGeek(IGeek geek) {
       this.geek = geek;
    }
}
This injects the CsvGFG bean into the GFG object using the setter
method (setGeek).
2. Constructor Dependency Injection (CDI):
Constructor DI involves injecting dependencies through constructors. To
configure CDI, the <constructor-arg> tag is used in the bean
configuration file.
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.IGeek;
public class GFG {
    // The object of the interface IGeek
    private IGeek geek;
    // Constructor to set the CDI
    public GFG(IGeek geek) {
       this.geek = geek;
    }
}
Bean Configuration:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="GFG" class="com.geeksforgeeks.org.GFG">
    <constructor-arg>
      <bean class="com.geeksforgeeks.org.impl.CsvGFG" />
    </constructor-arg>
  </bean>
<bean id="CsvGFG" class="com.geeksforgeeks.org.impl.CsvGFG" />
<bean id="JsonGFG" class="com.geeksforgeeks.org.impl.JsonGFG" />
</beans>
This injects the CsvGFG bean into the GFG object via the constructor.
Setter Dependency Injection (SDI) vs Constructor Dependency Injection
(CDI)
Setter DI                                       Constructor DI
                                                Good readability as it
 Poor readability as it adds a lot of
                                                is separately present in
 boiler plate codes in the application.
                                                the code.
                                                The bean class must
                                                declare a matching
 The bean must include getter and               constructor with
 setter methods for the properties.             arguments. Otherwise,
                                                BeanCreationException
                                                will be thrown.
 Requires addition of @Autowired                Best in the case of
 annotation, above the setter in the            loose coupling with
 code and hence, it increases the               the DI container as it is
 coupling between the class and the DI          not even required to
 container.                                     add @Autowired
                                                annotation in the
                                                code.( Implicit
                                                constructor injections
                                                for single constructor
     Setter DI                                     Constructor DI
                                                   scenarios after spring
                                                   4.0 )
                                                   No scope for circular
      Circular dependencies or partial
                                                   or partial dependency
      dependencies result with Setter DI
                                                   because dependencies
      because object creation happens
                                                   are resolved before
      before the injections.
                                                   object creation itself.
                                                   Preferred option when
                                                   properties on the bean
      Preferred option when properties are         are more and
      less and mutable objects can be              immutable objects (eg:
      created.                                     financial processes)
                                                   are important for
                                                   application.
5)   Auto Scanning
     Spring Component Scanning
     Spring 5 auto scanning using @Component annotation and XML
     configuration
     Spring framework has the functionality to auto-detect or auto scan the
     bean’s classes for injection
     using @Component annotation. @Component is a generic stereotype for
     any Spring-managed component. In the most of the previous example,
     we use the XML to specify the configuration metadata that produces
     each BeanDefinition within the Spring container manually.
     For auto scanning of beans, we need to add the context namespace
     schema to the root beans tag and scan the package. See the below
     configuration.
    <beans
      //...
      xmlns:context="http://www.springframework.org/schema/context"
      //...
    xsi:schemaLocation="http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-
    context.xsd">
      <!-- scan the package -->
           <context:component-scan base-
    package="org.websparrow.beans" />
          <!-- activate annotations -->
          <context:annotation-config />
    </beans>
    Whenever Spring container will load the configuration file, it will create
    the object of annotated beans.
    Note: It is application only for secondary type dependency injection. For
    primitive type we have to inject it manually.
    @ComponentScan and @EnableAutoConfiguration in Spring Boot
    Spring Annotations
    Annotations make it easier to configure the dependency injection in
    Spring. Instead of using XML configuration files, we can use Spring
    Bean annotations on classes and methods to define beans. After that,
    the Spring IoC container configures and manages the beans.
    Here’s an overview of the annotations that we are going to discuss in this
    article:
   @ComponentScan scans for annotated Spring components
   @EnableAutoConfiguration is used to enable the auto-configuration
    Let’s now look into the difference between these two annotations
    @ComponentScan
While developing an application, we need to tell the Spring framework to
look for Spring-managed components. @ComponentScan enables
Spring to scan for things like configurations, controllers, services, and
other components we define.
In particular, the @ComponentScan annotation is used
with @Configuration annotation to specify the package for Spring to
scan for components:
@Configuration
@ComponentScan
public class EmployeeApplication {
   public static void main(String[] args) {
     ApplicationContext context =
SpringApplication.run(EmployeeApplication.class, args);
     // ...
   }
}Copy
Alternatively, Spring can also start scanning from the specified package,
which we can define using basePackageClasses() or basePackages(). If
no package is specified, then it considers the package of the class
declaring the @ComponentScan annotation as the starting package:
@Component("employee")
public class Employee {
@EnableAutoConfiguration
The @EnableAutoConfiguration annotation enables Spring Boot to
auto-configure the application context. Therefore, it automatically
creates and registers beans based on both the included jar files in the
classpath and the beans defined by us.
For example, when we define the spring-boot-starter-web dependency in
our classpath, Spring boot auto-configures Tomcat and Spring MVC.
However, this auto-configuration has less precedence in case we define
our own configurations.
The package of the class declaring
the @EnableAutoConfiguration annotation is considered as the default.
Therefore, we should always apply
the @EnableAutoConfiguration annotation in the root package so that
every sub-packages and class can be examined.