Wednesday, November 29, 2017

Spring with GOUNTU

6. Spring MVC Tutorials 05 - Creating first Spring MVC Web Application using Eclipse IDE (01)



9. Spring MVC Tutorials 09 - @PathVariable annotation in detail (A URI-Template concept )




28.  Spring MVC Tutorials 28 - Exception Handling 01



------------------------------------------------------------------------------------------------------------

1. Spring With Hibernate Integration





-------------------------------------------------------------------

1. Spring Hibernate Part 1 - Introduction and Lesson Plan


2. Spring Hibernate Part 2: Architecture



3. Spring Hibernate Part 3 - Project Setup and Creating domain objects



4. Spring Hibernate Part 4 : Adding Persistence layer



5.  Spring Hibernate Part 5: Adding the Spring MVC




6. Spring Hibernate Part 6: MVC Screen Flow



7.  Spring-Hibernate-Part7: Service Layer





8. Spring-Hibernate-Part8 : Adding Validation



9.  Spring Hibernate Part 9 - Adding messages.properties and css stylesheets



10. Spring Tutorial Part1



Spring 1

1)      Spring   
2)      Struts2
3)      JSP
4)      Servlet

ZYAX4870 

SPRING

The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.

Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it.

In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept.

So, in summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.





Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)

The first thing that we do when we want to implement Spring MVC in our project is to add DispatcherServlets entry in deployment descriptor (web.xml). Also we write a spring web configuration xxxx-servlet.xml which contains all the MVC mappings and data.
By default the name of file must be XXX-servlet.xml where XXX is the name of servlet. For example in below entry in Web.xml we defined servlet named “spring”.
<servlet>
                               <servlet-name>spring</servlet-name>
                               <servlet-class>
                                              org.springframework.web.servlet.DispatcherServlet
                               </servlet-class>
                               <load-on-startup>1</load-on-startup>
               </servlet>
               <servlet-mapping>
                               <servlet-name>spring</servlet-name>
                               <url-pattern>*.html</url-pattern>
               </servlet-mapping>
 
Note that the servlet name is “spring” and thus, Spring will by default load file named “spring-servlet.xml” from your webapps WEB-INF folder.

What if we want to load a file called “bean.xml” instead of default “XXX-servlet.xml” ?

Well, this can be achieved by passing one init-parameter to spring’s DispatcherServlet. Check the following web.xml snippet.
<servlet>
                               <servlet-name>spring</servlet-name>
                               <servlet-class>
                                              org.springframework.web.servlet.DispatcherServlet
                               </servlet-class>
                               <init-param>
                                              <param-name>contextConfigLocation</param-name>
                                       <param-value>/WEB-INF/bean.xml</param-value>
                               </init-param>
                               <load-on-startup>1</load-on-startup>
               </servlet>
               <servlet-mapping>
                               <servlet-name>spring</servlet-name>
                               <url-pattern>*.html</url-pattern>
               </servlet-mapping>
 
Note that in above code snippet, we have passed an init-param to DispatcherServlet called contextConfigLocation. Using this parameter not only can we change the name of Spring’s web context file but also change its location.
This parameter will call setContextConfigLocation method on DispatcherServlet and overrides default context config file. Note that it is possible to add multiple locations separated by any number of commas and spaced.
<servlet>
                               <servlet-name>spring</servlet-name>
                               <servlet-class>
                                              org.springframework.web.servlet.DispatcherServlet
                               </servlet-class>
                               <init-param>
                                              <param-name>contextConfigLocation</param-name>
                                       <param-value>/WEB-INF/bean.xml, /WEB-INF/bean-service.xml, /WEB-INF/bean-dao.xml</param-value>
                               </init-param>
                               <load-on-startup>1</load-on-startup>
               </servlet>
               <servlet-mapping>
                               <servlet-name>spring</servlet-name>
                               <url-pattern>*.html</url-pattern>
               </servlet-mapping>
 
I hope this is useful :)



--------------------------------------------------------------------------------------------------------------------------

How Spring Controller Request Mapping works in Spring MVC

In the previous tutorial, we have discussed the role of a Dispatcher Servlet and the steps required to create a Spring MVC application. In this tutorial, we will discuss different type of request mapping to Spring controllers.
Dispatcher Servlet is used to handle all incoming requests and route them through Spring. When DispatcherServlet receives a web request, it determines which controllers should handle the incoming request.
It first scans for all classes that are declared with the @Controller annotation. The dispatching process depends on the various @RequestMapping annotations declared in a controller class and its handler methods. There are three levels of request mapping can be defined in Spring controller.
·         1. Handler level mapping
 Handler level mapping
The simplest strategy for using @RequestMapping annotations is to decorate the handler methods directly. In this method, you need to declare mapping for each handler method with the @RequestMapping annotation containing a URL pattern. If a handler’s @RequestMapping annotation matches the request URL, DispatcherServlet it dispatches the request to this handler for it to process the request.
Following are the different mapping types supported.
·         By path
@RequestMapping(“path”)
·         By HTTP method
@RequestMapping(“path”, method=RequestMethod.GET). Other Http methods such as POST, PUT, DELETE, OPTIONS, and TRACE are are also supported.
·         By query parameter
@RequestMapping(“path”, method=RequestMethod.GET, params=”param1”)
·         By presence of request header
@RequestMapping(“path”, header=”content-type=text/*”)
The request mapping for methods can be defined as follows:
@Controller
public class Employee {
 
               @RequestMapping("/employee/add")
               public ModelAndView add(
                                              @RequestParam(value = "firstName") String firstName,
                                              @RequestParam(value = "surName") String surName) {
                               //....
                               //....
                               return null;
               }
               @RequestMapping(value={"/employee/remove","/employee/delete"})
               public ModelAndView delete(
                                              @RequestParam(value = "uuid") String uuid) {
                               //....
                               //....
                               return null;
               }              
}
In the above code snippet, the controller add() method is declared with @RequestMapping("/employee/add"). If the incoming request path to matches is /employee/add, then the add() handler method will be invoked to process the request.
Handler mappings match URLs according to their paths relative to the context path (i.e., the path where the web application is deployed) and the servlet path (i.e., the path mapped to DispatcherServlet).
 Mapping at Controller class level
The @RequestMapping annotation can also be used to decorate a controller class. This is helpful to take the control at top level and filter the incoming requests. If the incoming request matches the pattern defined in controller class, then it search the controller methods mappings.
The following code snippet describes how to define Spring @RequestMapping at controller class level.
@Controller
@RequestMapping("/employee/*")
public class Employee {
               @RequestMapping("add")
               public ModelAndView add(
                                              @RequestParam(value = "firstName") String firstName,
                                              @RequestParam(value = "surName") String surName) {
                               //....
                               //....
                               return null;
               }
               @RequestMapping(value={"remove","delete"})
               public ModelAndView delete(
                                              @RequestParam(value = "uuid") String uuid) {
                               //....
                               //....
                               return null;
               }              
}
Notice that, we have used the wildcard (*) for the @RequestMapping annotation for broader URL matching.
Mapping requests by request type
The @RequestMapping annotation handles all types of incoming HTTP request including GET, POST, PUT, DELETE, PATCH etc. By default, it’s assumed all incoming requests to URLs are of the HTTP GET kind. To differentiate the mapping by HTTP request type, we need to explicitly specify the HTTP request method in the @RequestMapping declaration.
The following code snippet describes how to declare Spring mappings by HTTP request methods.
@Controller
@RequestMapping("/employee/*")
public class Employee {
 
               @RequestMapping(value = { "remove", "delete" }, method = { RequestMethod.POST,                RequestMethod.DELETE })
                               public ModelAndView delete(@RequestParam(value = "uuid") String uuid) {
                                              // ....
                                              // ....
                                                             return null;
                               }
}
"COMPONENT SCAN"




Which is the default handler mapping used by DispatcherServlet?
BeanNameUrlHandlerMapping
"By default the DispatcherServlet uses the BeanNameUrlHandlerMapping to map the incoming request. The BeanNameUrlHandlerMapping uses the bean name as the URL pattern. Since BeanNameUrlHandlerMapping is used by default, you need not do any seperate configuration for this."








Dispatcher Servlet

What is the front controller class of Spring MVC?

A front controller is defined as a controller that handles all requests for a Web Application. DispatcherServlet servlet is the front controller in Spring MVC that intercepts every request and then dispatches requests to an appropriate controller. When a web request is sent to a Spring MVC application, dispatcher servlet first receives the request. Then it organizes the different components configured in Spring?s web application context (e.g. actual request handler controller and view resolvers) or annotations present in the controller itself, all needed to handle the request.










The Spring Framework is a very comprehensive framework. The fundamental functionality provided by the Spring Container is dependency injection. Spring provides a light-weight container, e.g. the Spring core container, for dependency injection (DI). This container lets you inject required objects into other objects. This results in a design in which the Java class are not hard-coupled. The injection in Spring is either done via setter injection of via construction injection. These classes which are managed by Spring must conform to the JavaBean standard. In the context of Spring classes are also referred to as beans or as Spring beans.
The Spring core container:
·         handles the configuration, generally based on annotations or on an XML file (XMLBeanFactory)
·         manages the selected Java classes via the BeanFactory
The core container uses the so-called bean factory to create new objects. New objects are generally created as Singletons if not specified differently.


Class should be "Public" and "Public Constructor".


Dependency Inversion Principle

1.1         Motivation

When we design software applications we can consider the low level classes the classes which implement basic and primary operations(disk access, network protocols,...) and high level classes the classes which encapsulate complex logic(business flows, ...). The last ones rely on the low level classes. A natural way of implementing such structures would be to write low level classes and once we have them to write the complex high level classes. Since high level classes are defined in terms of others this seems the logical way to do it. But this is not a flexible design. What happens if we need to replace a low level class?
Let's take the classical example of a copy module which reads characters from the keyboard and writes them to the printer device. The high level class containing the logic is the Copy class. The low level classes are KeyboardReader and PrinterWriter.
In a bad design the high level class uses directly and depends heavily on the low level classes. In such a case if we want to change the design to direct the output to a new FileWriter class we have to make changes in the Copy class. (Let's assume that it is a very complex class, with a lot of logic and really hard to test).
In order to avoid such problems we can introduce an abstraction layer between high level classes and low level classes. Since the high level modules contain the complex logic they should not depend on the low level modules so the new abstraction layer should not be created based on low level modules. Low level modules are to be created based on the abstraction layer.
According to this principle the way of designing a class structure is to start from high level modules to the low level modules:
High Level Classes --> Abstraction Layer --> Low Level Classes

1.2         Intent

·         High-level modules should not depend on low-level modules. Both should depend on abstractions.
·         Abstractions should not depend on details. Details should depend on abstractions.

1.3         Example

Below is an example which violates the Dependency Inversion Principle. We have the manager class which is a high level class, and the low level class called Worker. We need to add a new module to our application to model the changes in the company structure determined by the employment of new specialized workers. We created a new class SuperWorker for this.
Let's assume the Manager class is quite complex, containing very complex logic. And now we have to change it in order to introduce the new SuperWorker. Let's see the disadvantages:
·         We have to change the Manager class (remember it is a complex one and this will involve time and effort to make the changes).
·         Some of the current functionality from the manager class might be affected.
·         The unit testing should be redone.
All those problems could take a lot of time to be solved and they might induce new errors in the old functionality. The situation would be different if the application had been designed following the Dependency Inversion Principle. It means we design the manager class, an IWorker interface and the Worker class implementing the IWorker interface. When we need to add the SuperWorker class all we have to do is implement the IWorker interface for it. No additional changes in the existing classes.

// Dependency Inversion Principle - Bad example

  

  
classWorker {

  

  
               publicvoidwork() {

  

  
                               //....working

  

  
               }
}

  

  
ClassManager {

  

  
               Workerworker;

  

  
               PublicvoidsetWorker(Workerw)
        {
          worker=w;

                 }

  

                 publicvoidmanage(){

                                 worker.work();

                 }

}

  

classSuperWorker {

                 publicvoidwork(){

                                 //....working much more

                 }

}

  

Below is the code which supports the Dependency Inversion Principle. In this new design a new abstraction layer is added through the IWorker Interface. Now the problems from the above code are solved(considering there is no change in the high level logic):
·         Manager class doesn't require changes when adding SuperWorkers.
·         Minimized risk to affect old functionality present in Manager class since we don't change it.
·         No need to redo the unit testing for Manager class.
//DependencyInversionPrinciple-Goodexample
inte
rfaceIWorker{

                          publicvoidwork();

}

  

classWorkerimplementsIWorker{

                          publicvoidwork() {

                                          // ....working

                          }

}

  

classSuperWorkerimplementsIWorker{

                          publicvoidwork() {

                                          //....workingmuch more

                          }

}

  

classManager{

                          IWorkerworker;

  

                          publicvoidsetWorker(IWorkerw) {

                                          worker=w;

                          }

  

                          publicvoidmanage() {

                                          worker.work();

                          }

}

  

  

1.1         Conclusion

When this principle is applied it means the high level classes are not working directly with low level classes, they are using interfaces as an abstract layer. In this case instantiation of new low level objects inside the high level classes (if necessary) cannot be done using the operator new. Instead, some of the Creational design patterns can be used, such as Factory Method, Abstract Factory, Prototype.
The Template Design Pattern is an example where the DIP principle is applied.
Of course, using this principle implies an increased effort, will result in more classes and interfaces to maintain, in a few words in more complex code, but more flexible. This principle should not be applied blindly for every class or every module. If we have a class functionality that is more likely to remain unchanged in the future there is not need to apply this principle.
Spring Annotations: Contents:
ANNOTATION
USE
DESCRIPTION
@Autowired
Constructor, Field, Method
Declares a constructor, field, setter method, or configuration method to be autowired by type. Items annotated with @Autowired do not have to be public.
@Configurable
Type
Used with <context:springconfigured> to declare types whose properties should be injected, even if they are not instantiated by Spring. Typically used to inject the properties of domain objects.
@Order
Type, Method, Field
Defines ordering, as an alternative to implementing the org. springframework.core.Ordered interface.
@Qualifier
Field, Parameter, Type, Annotation Type
Guides autowiring to be performed by means other than by type.
@Required
Method (setters)
Specifies that a particular property must be injected or else the configuration will fail.
@Scope
Type
Specifies the scope of a bean, either singleton, prototype, request, session, or some custom scope.
Annotation
Package Detail/Import statement
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.security.access.prepost.PreAuthorize;
For spring to process annotations, add the following lines in your application-context.xml file.
               <context:annotation-config />
               <context:component-scan base-package="...specify your package name..." />
Spring supports both Annotation based and XML based configurations. You can even mix them together. Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.

@Service

Annotate all your service classes with @Service. All your business logic should be in Service classes.
@Service
public class CompanyServiceImpl implements CompanyService {
...
}

@Repository

Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
@Repository
public class CompanyDAOImpl implements CompanyDAO {
...
}

@Component

Annotate your other components (for example REST resource classes) with @Component.
@Component
public class ContactResource {
...
}
@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively. 

@Autowired

Let Spring auto-wire other beans into your classes using @Autowired annotation. 
@Service
public class CompanyServiceImpl implements CompanyService {
  @Autowired
  private CompanyDAO companyDAO;
   
  ...
}
Spring beans can be wired by name or by type.
  • @Autowire by default is a type driven injection. @Qualifier spring annotation can be used to further fine-tune autowiring.
  • @Resource (javax.annotation.Resource) annotation can be used for wiring by name.
Beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.

@Transactional

Configure your transactions with @Transactional spring annotation.
@Service
public class CompanyServiceImpl implements CompanyService {
  @Autowired
  private CompanyDAO companyDAO;
  @Transactional
  public Company findByName(String name) {
    Company company = companyDAO.findByName(name);
    return company;
  }
  ...
}
To activate processing of Spring's @Transactional annotation, use the <tx:annotation-driven/> element in your spring's configuration file.

The default @Transactional settings are as follows:
  • Propagation setting is PROPAGATION_REQUIRED.
  • Isolation level is ISOLATION_DEFAULT.
  • Transaction is read/write.
  • Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported.
  • Any RuntimeException triggers rollback, and any checked Exception does not.
These default settings can be changed using various properties of the @Transactional spring annotation. 

Specifying the @Transactional annotation on the bean class means that it applies to all applicable business methods of the class. Specifying the annotation on a method applies it to that method only. If the annotation is applied at both the class and the method level, the method value overrides if the two disagree.

@Scope

As with Spring-managed components in general, the default and most common scope for autodetected components is singleton. To change this default behavior, use @Scope spring annotation.
@Component
@Scope("request")
public class ContactResource {
...
}
Similarly, you can annotate your component with @Scope("prototype") for beans with prototype scopes.
Please note that the dependencies are resolved at instantiation time. For prototype scope, it does NOT create a new instance at runtime more than once. It is only during instantiation that each bean is injected with a separate instance of prototype bean.

Spring MVC Annotations

@Controller

Annotate your controller classes with @Controller.
@Controller
public class CompanyController {
...
}

@RequestMapping

You use the @RequestMapping spring annotation to map URLs onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping.
@Controller
@RequestMapping("/company")
public class CompanyController {

  @Autowired
  private CompanyService companyService;
...
}

@PathVariable

You can use the @PathVariable spring annotation on a method argument to bind it to the value of a URI template variable. In our example below, a request path of /company/techferry will bind companyName variable with 'techferry' value.
@Controller
@RequestMapping("/company")
public class CompanyController {

  @Autowired
  private CompanyService companyService;

  @RequestMapping("{companyName}")
  public String getCompany(Map<String, Object> map,
            @PathVariable String companyName) {
    Company company = companyService.findByName(companyName);
    map.put("company", company);
    return "company";
  }
...
}

@RequestParam

You can bind request parameters to method variables using spring annotation @RequestParam.
@Controller
@RequestMapping("/company")
public class CompanyController {

  @Autowired
  private CompanyService companyService;

  @RequestMapping("/companyList")
  public String listCompanies(Map<String, Object> map,
            @RequestParam int pageNum) {
    map.put("pageNum", pageNum);
    map.put("companyList", companyService.listCompanies(pageNum));
    return "companyList";
  }
...
}
Similarly, you can use spring annotation @RequestHeader to bind request headers.
@ModelAttribute
An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.
@Controller
@RequestMapping("/company")
public class CompanyController {

  @Autowired
  private CompanyService companyService;

  @RequestMapping("/add")
  public String saveNewCompany(@ModelAttribute Company company) {
    companyService.add(company);
    return "redirect:" + company.getName();
  }
...
}

@SessionAttributes

@SessionAttributes spring annotation declares session attributes. This will typically list the names of model attributes which should be transparently stored in the session, serving as form-backing beans between subsequent requests.
@Controller
@RequestMapping("/company")
@SessionAttributes("company")
public class CompanyController {

  @Autowired
  private CompanyService companyService;
...
}
@SessionAttribute works as follows:
  • @SessionAttribute is initialized when you put the corresponding attribute into model (either explicitly or using @ModelAttribute-annotated method).
  • @SessionAttribute is updated by the data from HTTP parameters when controller method with the corresponding model attribute in its signature is invoked.
@SessionAttributes are cleared when you call setComplete() on SessionStatus object
  • passed into controller method as an argument.

The following listing illustrate these concepts. It is also an example for pre-populating Model objects.
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

    @ModelAttribute("types")
     
    public Collection<PetType> populatePetTypes() {
        return this.clinic.getPetTypes();
    }
     
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet,
            BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId="
                + pet.getOwner().getId();
        }
    }
}

Spring Security Annotations


@PreAuthorize


Using Spring Security @PreAuthorize annotation, you can authorize or deny a functionality. In our example below, only a user with Admin role has the access to delete a contact.
@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void removeContact(Integer id) {
  contactDAO.removeContact(id);
}



Loose Coupling and Tight Coupling



Core Module is the heart of Spring,  tight coupling and loose coupling is the heart concept          of Core Module :-)  so let us try to understand about tight and loose coupling between java objects in spring [ you can't move further without understand this concepts, be care ]

Tight Coupling Between Java Objects

Let us see tight coupling between java objects first, take an example..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Traveler
{
    Car c=new Car();
    void startJourney()
    {
       c.move();
    }
}

class Car
{
  void move()
  {
     // logic...
  }
}

·         In the above example, Traveler object is depends on car object.  So traveler class creating an object of Car class inside it [ line number 3 ]

·         If the other class object is created in the dependent class [ like Car class object in Traveler class ], there exist tight coupling, i mean if method in car object is changed then we need to do the changes in the Traveler class too so its the tight coupling between Traveler and Car class objects

Loose Coupling between Java Objects

Let us see loose coupling between java objects, take an example..

In order to overcome tight coupling between objects, spring framework uses dependency injection mechanism with the help of POJO/POJI model and through dependency injectionits possible to achieve loose coupling

In the above example Traveler, Car is tightly coupled.  If we want to achieve loose coupling between the objects Traveler and Car, we need to re-write the application like….


1
2
3
4
5
6
7
8
9
10
11
12
13
class Traveler
{
    Vehicle v;
    public void setV(Vehicle v)
    {
      this.v = v;
    }      

    void startJourney()
    {
       v.move();
    }
}


------------------
1
2
3
4
Interface Vehicle
{
   void move();
}
 -----------------------------


1
2
3
4
5
6
7

class Car implements Vehicle
{
public void move()
{
// logic
}
}


1
2
3
4
5
6
7
class Bike implements Vehicle
{
    public void move()
    {
         // logic
    }
}


-----------------------------------------Eclipse test--------------------------------------------------------------

packagecom.test.Intfce;

publicclassTestLooseCoupling {

            Vehicle v ;
            publicvoidsetV(Vehicle v)
            {
                        this.v = v;
            }
                        publicvoidstartJourny()
            {
                        v.move();
            }
            publicstaticvoid main(String[] args) {

                        TestLooseCouplingtlc = newTestLooseCoupling();
                        tlc.setV(new Car());
                        //tlc.setV(new Bike());
                        tlc.startJourny();
            }
}

packagecom.test.Intfce;
publicinterface Vehicle {
            publicvoid move();
}


packagecom.test.Intfce;
publicclass Car implements Vehicle {
            @Override
            publicvoid move() {
                        System.out.println("Calling from Car");
            }
}
packagecom.test.Intfce;
publicclass Bike implements Vehicle {
            @Override
            publicvoid move() {
                        System.out.println("Calling from Bike");
                       
            }
}
------------------------------------------End Eclipse test-------------------------------------------------------
1
2
3
4
5
6
7
class Bike implements Vehicle
{
    public void move()
    {
         // logic
    }
}


-----------------------------------------Eclipse test--------------------------------------------------------------

packagecom.test.Intfce;

publicclassTestLooseCoupling {

            Vehicle v ;
            publicvoidsetV(Vehicle v)
            {
                        this.v = v;
            }
                        publicvoidstartJourny()
            {
                        v.move();
            }
            publicstaticvoid main(String[] args) {

                        TestLooseCouplingtlc = newTestLooseCoupling();
                        tlc.setV(new Car());
                        //tlc.setV(new Bike());
                        tlc.startJourny();
            }
}

packagecom.test.Intfce;
publicinterface Vehicle {
            publicvoid move();
}


packagecom.test.Intfce;
publicclass Car implements Vehicle {
            @Override
            publicvoid move() {
                        System.out.println("Calling from Car");
            }
}
packagecom.test.Intfce;
publicclass Bike implements Vehicle {
            @Override
            publicvoid move() {
                        System.out.println("Calling from Bike");
                       
            }
}
------------------------------------------End Eclipse test-------------------------------------------------------
In above example, spring container will inject either Car object or Bike object into theTraveler by calling setter method, So if Car object is replaced with Bike then no changes are required in Traveler class, this means there is loose coupling between Traveler and Vehicle object.  Actually setter method will be activated through xml file, will see this later for now we are good to go 



1.1         Tight-coupling and Loose-coupling between objects

1.2         Tight-Coupling:-


1.    While creating complex application in java, the logic of one class will call the logic of another class to provide same service to the clients.

2.    If one class calling another class logic then it is called collaboration.

3.    When one class is collaborating with another class then there exists tight-coupling between the two classes.

4.    If one class wants to call the logic of a second class then they first class need an object of second class it means the first class create an object of second class.

5.    For example, if we have two classes called traveller and car, traveller class is calling logic of car class; in this case traveller class creates an object of car class.

6.      In the above traveller class and car classes, car class object of dependency for traveller object.

Example:-
7.    In the above example traveller object is tightly coupled with car object because in place car object  if you want to use bike object then, we need to make changes in Traveller class

    Example :-

1.3         Loose-Coupling:-


1.    In Loose-Coupling, when one object is depending on another class object, some external entity will provide that dependency object to the main object that external object we call as a Container.

2.    In order to get loose-coupling between objects the following two rules are required

1.    The classes should follow POJI/POJO model.

2.    Apply dependency injection mechanism.

 For example:-
3.    In the above traveler class, an external entity injects either car (or) Bike object.

4.    In traveler, these are no changes required we are shifting the dependency from car to a Bike.

5.    In the above traveler class, we are token vehicle reference, so that an external object (Container) can injects either car object (or) Bike object, depends on requirement if a traveler.

6.    In spring frame work, spring container follows dependency injection mechanism and injects the dependency objects required for a main object.

7.    Spring frame work is much success because of one of the main reason is it promotes Loose-Coupling between the objects.



Spring HelloWorld Program.
HelloWorld.java
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message  = message;
   }
public void getMessage(){
System.out.println("Your Message : " + message);
   }
}
MainApp.java

importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
newClassPathXmlApplicationContext("Beans.xml");
HelloWorldobj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
   }
}
·         First step is to create application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects ie. beans mentioned in the configuration file.
·         Second step is used to get required bean using getBean() method of the created context. This method uses bean ID to return a generic object which finally can be casted to actual object. Once you have object, you can use this object to call any class method.
Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">

<bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>

OutPut:
Your Message : Hello World!

Spring Container
The spring container is at the core of the Spring Framework. The container will create 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.
The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations or Java code.
The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application.
Beans
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/> definition.
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
Spring Configuration Metadata
Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. There are following three important methods to provide configuration metadata to the Spring Container:
·         XML based configuration file.
·         Annotation-based configuration
·         Java-based configuration
sample of XML based configuration file with different bean definitions including lazy initialization, initialization method and destruction method:
<?xml version="1.0" encoding="UTF-8"?>

<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-3.0.xsd">

<!-- A simple bean definition -->
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with lazy init set on -->
<bean id="..." class="..." lazy-init="true">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with initialization method -->
<bean id="..." class="..." init-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with destruction method -->
<bean id="..." class="..." destroy-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->

</beans>

Autowiring

Advantages of Autowiring

  • Autowiring requires less code because we don’t need to write the code to inject the dependency explicitly.
  • It reduces develop time by removing the necessity of specifying properties and constructor arguments.

Disadvantages of Autowiring

  • Autowiring is less exact than explicit wiring. Spring is careful to avoid guessing in the case of ambiguity that might have unexpected results, the relationships between Spring-managed objects are no longer document explicitly.
  • Wiring information may not be available to tools that generate documentation from a Spring container.
  • Multiple bean definition within the container may match the type specified by the constructor or setter method argument to be autowired.

Limitations With Autowiring

  • Explicit dependencies in constructor-argument and property settings always override autowiring. You cannot autowire simple properties such as primitives, Strings, and Classes.
  • Overriding possibilities: We can define dependencies using property or constructor-args tag which will always override autowiring.
  • Primitive data type: We have to define primitive data types String or Integer using property or constructor-args tag. You cannot autowire these tags.
  • Confusing Nature: If you have lot of dependency in a program, then it’s hard to find using autowire attribute of bean.

Autowiring

  • Spring can autowire a relationship between collaborating beans without using constructor-arg and property tags which helps with the amount of XML configuration.
  • You can allow Spring to resolve collaborators automatically for your bean by inspecting the contents of the Application Context.
  • Autowiring of the Spring framework enables you to inject the object dependency implicitly. Autowiring needs significantly less specification with properties or constructor arguments.
  • Autowiring can update configuration as your objects. For example, if you need to add a dependency to a class, that dependency can automatically satisfy your need to modify the configuration. Autowiring can be especially useful during development, without negation the option of switching to explicit wiring when the code becomes more stable.


Autowiring Modes

Modes
Description
1.
No
It’s a default autowiring mode. It means no autowiring.
2.
byName
Autowiring using property name. Spring container looks the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It tries to match and wire its properties with the beans defined by the same name in the configuration file.
3.
byType
Autowiring using property type. Allows a property to be autowired if exactly one bean of property type exists in the container. If more than one exists, it’s a fatal exception is thrown, which indicates that you may not used byType autowiring for that bean.
4.
constructor
Tries to match a constructor of the autowired bean with
beans whose types are assignable to the constructor arguments. There is not exactly one bean of the constructor argument in the container, a fatal error is raise.
5.
autodetect
Spring first tries to autowire by constructor, if it doesn't work then If that fails than tries to autowired by using byType.

Example of Autowiring

public class Book
{
            private Author author;
            public Book(Author author) {
                        this. customer = customer;
            }
            public void setAuthor (Author author) {
                        this.author = author;
            }
            //.......
}
public class Author
{
            //......
}
1. Auto-Wiring ‘no’
This is a default autowiring mode. It means no autowiring.
<bean id="book" class="com.spring.common.Book">
                  <property name="Java" ref="completereference"/>
</bean>
<bean id="author" class="com.spring.common.Author" />
2. Auto-Wiring ‘byName’
In the Spring framework, everything is given a name. Bean properties are given a name and the beans that are wired to those properties, too.
The name of a property happens to match the names of the bean that is to be wired to that property. Spring framework that the bean should be automatically wired into the property.
Autowired a bean by property name. In this case, since the name of the "author" bean is the same name of the “book” bean’s property (“Author”), Spring will be autowired to it via the setter method – “setAuthor (Author author)”.
<bean id="book" class="com.spring.common.Book" autowire="byName" />  
<bean id="author" class="com.spring.common.Author" />
3. Auto-Wiring ‘byType
  • Autowiring using byType works similarly to byName. When attempting to autowire a property byType, Spring will look T beans whose type is assigned to the property’s type.
  • Autowire a bean by data type. In this case, the data type of the “author” bean is the same as the data type of the “book” bean’s property (Author object), so, Spring will autowire it via the setter method – “setAuthor (Author author)“.
<bean id="book" class="com.spring.common.Book" autowire="byType" />
<bean id="author" class="com.spring.common.Author" />
4. Auto-Wiring ‘constructor’
  • If your bean is configured using a constructor injection, you may choose to put the <constructor-arg> elements.constructor arguments from beans in the Spring context.
  • Autowire a bean by property data type in constructor arguments. Since the data type of “author” bean is same as the constructor argument data type in “book” bean’s property (Author object), Spring autowired it using the constructor method – “public Book(Author author)“.
<bean id="vehicle" class="com.spring.common.Vehicle" autowire="constructor" />
<bean id="author" class="com.spring.common.Author" />
5. Auto-Wiring ‘autodetect’
  • If you want to autowire beans, but you can’t decide which type of autowiring to use, have no fear. We can set the autowire attribute to autodetect.
  • If a default constructor is found, it first tries to autowire by “constructor”; otherwise, if it doesn't work but fails, then it tries to autowire using “byType”. In this case, since there is a default constructor in the “Book” class, Spring autowired it via the constructor method – “public Book (Author author) “.
<bean id="vehicle" class="com.spring.common.Vehicle" autowire="autodetect" />
<bean id="author" class="com.spring.common.Author" />
You just learned about autowiring and how to use it in Java web development (Spring). Don’t forget to give credit to the Java development team that worked hard to help you understand the advantages, limitations, and disadvantages of autowiring.

Autowiring in Spring Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection. Autowiring can't be used to inject primitive and string values. It works with reference only.
Advantage of Autowiring It requires the less code because we don't need to write the code to inject the dependency explicitly.


----------------------------------------------------------------------------------------------------------------------------

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

1.    What do you understand by Dependency Injection?

Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.
Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate Code reduction, Configurable components and easy unit testing.
Read more at Dependency Injection Tutorial. We can also use Google Guide for Dependency Injectionto automate the process of dependency injection. But in most of the cases we are looking for more than just dependency injection and that’s why Spring is the top choice for this.

2.    How do we implement DI in Spring Framework?

We can use Spring XML based as well as Annotation based configuration to implement DI in spring applications. For better understanding, please read Spring Dependency Injection example where you can learn both the ways with JUnit test case. The post also contains sample project zip file, that you can download and play around to learn more.

2           Spring - Bean Scopes

The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.
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 ApplicationContext.
Session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session
This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
The singleton scope:
If scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.
The default scope is always singleton however, when you need one and only one instance of a bean, you can set the scope property to singleton in the bean configuration file, as shown below:
<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>

Example of Scope :
HelloWorld.java

public class HelloWorld {
private String message;
public void setMessage(String message){
this.message  = message;
   }
public void getMessage(){
System.out.println("Your Message : " + message);
   }
}

MainApp.java
importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

objA.setMessage("I'm object A");
objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
objB.getMessage();
   }
}

Beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld"
scope="singleton">
</bean>
</beans>

Output:
Your Message : I'm object A
Your Message : I'm object A

2.1         The prototype scope:

If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.
To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown below:
<!-- A bean definition with singleton scope -->
<beanid="..."class="..."scope="prototype">
<!-- collaborators and configuration for this bean go here -->
</bean>

difference between session and global session in spring

globalSession is something which is connected to Portlet applications. When your application works in Portlet container it is built of some amount of portlets. Each portlet has its own session, but if your want to store variables global for all portlets in your application than you should store them in globalSession. This scope doesn't have any special effect different from session scope in Servlet based applications.


session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
Portlet container runs portlets and provides them with the required runtime 

environment. 

A portlet container contains portlets and manages their life cycles. It also provides persistent 

storage mechanisms for the portlet preferences. A portlet container receives requests from 

the portal to execute requests on the portlets hosted by it. A portlet container is not 

responsible for aggregating the content produced by the portlets; the portal itself handles 

aggregation. A portal and a portlet container can be built together as a single component of 

an application suite or as two separate components of a portal application.
Portlets are pluggable user interface software components that are managed and displayed 

in a web or enterprise portal.
Portlets produce fragments of markup (HTMLXHTMLWML) code that are aggregated into a 
portal. Typically, following the desktop metaphor, a portal page is displayed as a collection of 

non-overlapping portlet windows, where each portlet window displays a portlet. Hence a 

portlet (or collection of portlets) resembles a web-based application that is hosted in 

portal.

Some examples of portlet applications are e-mailweather reportsdiscussion forums

and news.
Portlet standards are intended to enable software developers to create portlets that can 

be plugged into any portal supporting the standards.

Portlet-based solutions are an example of component-based software engineering.


Spring - Bean Life Cycle

--------------------------------------------------------------------------------------------------------------------

2.2         Overview of Spring Bean Life Cycle

Life of traditional java objects starts on calling new operator which instantiates the object and finalize() method is getting called when the object is eligible for garbage collection. Life cycle of Spring beans are different as compared to traditional java objects.
Spring framework provides the following ways which can be used to control the lifecycle of  bean:
1.      InitializingBean and DisposableBean callback interfaces
2.      Bean Name, bean factory and Application Context  Aware interfaces for specific behavior
3.      custom init() and destroy() methods in bean configuration file
For annotation based configurations -
@PostConstruct and @PreDestroy annotations
Below diagram shows the complete lifecycle methods (from instantiate to Ready To use )
Following diagram shows the method calling  at the time of destruction.

--------------------------------


The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.
Though, there is lists of the activities that take place behind the scenes between the time of bean Instantiation and its destruction, but this chapter will discuss only two important bean lifecycle callback methods which are required at the time of bean initialization and its destruction.
To define setup and teardown for a bean, we simply declare the <bean> with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.

2.3         Initialization callbacks:

The org.springframework.beans.factory.InitializingBean interface specifies a single method:
voidafterPropertiesSet()throwsException;

So you can simply implement above interface and initialization work can be done inside afterPropertiesSet() method as follows:
 
publicclassExampleBeanimplementsInitializingBean{
publicvoidafterPropertiesSet(){
// do some initialization work
}
}


In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example:
 
<beanid="exampleBean"
class="examples.ExampleBean"init-method="init"/>

Following is the class definition:
 
publicclassExampleBean{
publicvoidinit(){
// do some initialization work
}
}

2.4          

2.5         Destruction callbacks

The org.springframework.beans.factory.DisposableBean interface specifies a single method:
 
void destroy()throwsException;

So you can simply implement above interface and finalization work can be done inside destroy() method as follows:
publicclassExampleBeanimplementsDisposableBean{
publicvoid destroy(){
// do some destruction work
}
}
In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example:
<beanid="exampleBean"
class="examples.ExampleBean"destroy-method="destroy"/>

3           Spring - Dependency Injection

Every java based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while doing unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and same time keeping them independent.
Consider you have an application which has a text editor component and you want to provide spell checking. Your standard code would look something like this:

public class TextEditor {
privateSpellCheckerspellChecker;

publicTextEditor() {
spellChecker = new SpellChecker();
   }
}
What we've done here is create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario we would instead do something like this:
public class TextEditor {
privateSpellCheckerspellChecker;

publicTextEditor(SpellCheckerspellChecker) {
this.spellChecker = spellChecker;
   }
}
Here TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to TextEditor at the time of TextEditor instantiation and this entire procedure is controlled by the Spring Framework.
Here, we have removed the total control from TextEditor and kept it somewhere else (ie. XML configuration file) and the dependency ( ie. class SpellChecker) is being injected into the class TextEditor through a Class Constructor. Thus flow of control has been "inverted" by Dependency Injection (DI) because you have effectively delegated dependence’s to some external system.
Second method of injecting dependency is through Setter Methods of TextEditor class where we will create SpellChecker instance and this instance will be used to call setter methods to initialize TextEditor's properties.
Thus, DI exists in two major variants and following two sub-chapters will cover both of them with examples:
Dependency Injection Type & Description
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 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.
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.
Code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies, and does not know the location or class of the dependencies rather everything is taken care by the Spring Framework.

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

TextEditor.java
packagecom.tutorialspoint;

public class TextEditor {
privateSpellCheckerspellChecker;

publicTextEditor(SpellCheckerspellChecker) {
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
   }
public void spellCheck() {
spellChecker.checkSpelling();
   }
}


SpellChecker.java
packagecom.tutorialspoint;

public class SpellChecker {
publicSpellChecker(){
System.out.println("Inside SpellChecker constructor." );
   }

public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
   }

MainApp.java
packagecom.tutorialspoint;

importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
newClassPathXmlApplicationContext("Beans.xml");

TextEditorte = (TextEditor) context.getBean("textEditor");

te.spellCheck();
   }
}


Beans.xml
<?xml version="1.0" encoding="UTF-8"?>

<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-3.0.xsd">

<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<constructor-arg ref="spellChecker"/>
</bean>

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>

</beans>

OutPut :
Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

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

TextEditor.java

packagecom.tutorialspoint;

public class TextEditor {
privateSpellCheckerspellChecker;

   // a setter method to inject the dependency.
public void setSpellChecker(SpellCheckerspellChecker) {
System.out.println("Inside setSpellChecker." );
this.spellChecker = spellChecker;
   }
   // a getter method to return spellChecker
publicSpellCheckergetSpellChecker() {
returnspellChecker;
   }

public void spellCheck() {
spellChecker.checkSpelling();
   }
}

SpellChecker.java
packagecom.tutorialspoint;

public class SpellChecker {
publicSpellChecker(){
System.out.println("Inside SpellChecker constructor." );
   }

public void checkSpelling() {
System.out.println("Inside checkSpelling." );
   }
}

MainApp.java
packagecom.tutorialspoint;

importorg.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
newClassPathXmlApplicationContext("Beans.xml");

TextEditorte = (TextEditor) context.getBean("textEditor");

te.spellCheck();
   }
}

Beans.xml
<?xml version="1.0" encoding="UTF-8"?>

<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-3.0.xsd">

<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<property name="spellChecker" ref="spellChecker"/>
</bean>

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>

</beans>

AUTO - Wiring
Following is the configuration file Beans.xml in normal condition:
<?xml version="1.0" encoding="UTF-8"?>
 
<beansxmlns="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-3.0.xsd">
 
<!-- Definition for textEditor bean -->
<beanid="textEditor"class="com.tutorialspoint.TextEditor">
<propertyname="spellChecker"ref="spellChecker"/>
<propertyname="name"value="Generic Text Editor"/>
</bean>
 
<!-- Definition for spellChecker bean -->
<beanid="spellChecker"class="com.tutorialspoint.SpellChecker">
</bean>
 
</beans>

6           Spring Autowiring 'byName'

But if you are going to use autowiring 'byName', then your XML configuration file will become as follows:
<?xml version="1.0" encoding="UTF-8"?>
 
<beansxmlns="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-3.0.xsd">
 
<!-- Definition for textEditor bean -->
<beanid="textEditor"class="com.tutorialspoint.TextEditor"
autowire="byName">
<propertyname="name"value="Generic Text Editor"/>
</bean>
 
<!-- Definition for spellChecker bean -->
<beanid="spellChecker"class="com.tutorialspoint.SpellChecker">
</bean>
</beans>
 

7           Spring Autowiring 'byType'

 
<?xml version="1.0" encoding="UTF-8"?>
 
<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-3.0.xsd">
 
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor" 
autowire="byType">
<property name="name" value="Generic Text Editor" />
</bean>
 
<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
 
</beans>

8           Spring Autowiring by Constructor

 
<?xml version="1.0" encoding="UTF-8"?>

<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-3.0.xsd">

<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor"
autowire="constructor">
<constructor-arg value="Generic Text Editor"/>
</bean>

<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
</beans>



Spring MVC
In Spring Web MVC, DispatcherServlet class works as the front controller. It is responsible to manage the flow of the spring mvc application.
The @Controller annotation is used to mark the class as the controller in Spring 3.
The @RequestMapping annotation is used to map the request url. It is applied on the method.


Understanding the flow of Spring Web MVC

 

1) Create the request page (optional)

This is the simple jsp page containing a link. It is optional page. You may direct invoke the action class instead.
index.jsp
  1. <a href="hello.html">click</a>  


2) Create the controller class

To create the controller class, we are using two annotations @Controller and @RequestMapping.
The @Controller annotation marks this class as Controller.
The @Requestmapping annotation is used to map the class with the specified name.
This class returns the instance of ModelAndView controller with the mapped name, message name and message value. The message value will be displayed in the jsp page.
HelloWorldController.java
  1. package com.javatpoint;  
  2. import org.springframework.stereotype.Controller;  
  3. import org.springframework.web.bind.annotation.RequestMapping;  
  4. import org.springframework.web.servlet.ModelAndView;  
  5. @Controller  
  6. public class HelloWorldController {  
  7.     @RequestMapping("/hello")  
  8.     public ModelAndView helloWorld() {  
  9.         String message = "HELLO SPRING MVC HOW R U";  
  10.         return new ModelAndView("hellopage""message");  
  11.     }  
  12. }  


3) Provide the entry of controller in the web.xml file

In this xml file, we are specifying the servlet class DispatcherServlet that acts as the front controller in Spring Web MVC. All the incoming request for the html file will be forwarded to the DispatcherServlet.
web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.  <servlet>  
  8.     <servlet-name>spring</servlet-name>  
  9.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  10.     <load-on-startup>1</load-on-startup>  
  11. </servlet>  
  12. <servlet-mapping>  
  13.     <servlet-name>spring</servlet-name>  
  14.     <url-pattern>*.html</url-pattern>  
  15. </servlet-mapping>  
  16. </web-app>  


4) Define the bean in the xml file

This is the important configuration file where we need to specify the ViewResolver and View components.
The context:component-scan element defines the base-package where DispatcherServlet will search the controller class.
Here, the InternalResourceViewResolver class is used for the ViewResolver.
The prefix+string returned by controller+suffix page will be invoked for the view component.
This xml file should be located inside the WEB-INF directory.
spring-servlet.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8. http://www.springframework.org/schema/context  
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  10.     <context:component-scan  base-package="com.javatpoint" />  
  11.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  12.         <property name="prefix" value="/WEB-INF/jsp/" />  
  13.         <property name="suffix" value=".jsp" />  
  14.     </bean>  
  15. </beans>  

5) Display the message in the JSP page

This is the simple JSP page, displaying the message returned by the Controller.
It must be located inside the WEB-INF/jsp directory for this example only.
hellopage.jsp
  1. Message is: ${message} 


Question 5: What are different modules in spring?
Answer : spring have seven core modules
1.      The Core container module
2.      Application context module
3.      AOP module (Aspect Oriented Programming)
4.      JDBC abstraction and DAO module
5.      O/R mapping integration module (Object/Relational)
6.      Web module
7.      MVC framework module

4) What are the core interfaces of Hibernate?
The core interfaces of Hibernate framework are:
  • Configuration
  • SessionFactory
  • Session
  • Query
  • Criteria
  • Transaction
3) What are the steps to connect to the database in java?
  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection

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
It’s not
Support application life-cycle events, and validation.
Doesn’t support.
Support  many enterprise services such JNDI access, EJB integration, remoting
Doesn’t support.

Question 7: What type of transaction Management Spring support?
Ans: This spring interview questions is little difficult as compared to previous questions just because transaction management is a complex concept and not every developer familiar with it. Transaction management is critical in any applications that will interact with the database. The application has to ensure that the data is consistent and the integrity of the data is maintained.  Two type of transaction management is supported by spring

1. Programmatic transaction management
2. Declarative transaction management.

In Spring, the Inversion of Control (IoC) principle is implemented using the Dependency Injection (DI) design pattern. Let's understand dependency injection with the help of an example. First we will see a java version of the example and later we will add spring functionalities to it. As far as the example go, its pretty simple. The QuizMater interface exposes the popQuestion() method. To keep things simple, our QuizMaster will generate only one question.
QuizMaster.java
----------------
packagecom.vaannila;

public interface QuizMaster {

               public String popQuestion();
}
The StrutsQuizMaster and the SpringQuizMaster class implements QuizMaster interface and they generate questions related to struts and spring respectively.
StrutsQuizMaster.java
----------------------
packagecom.vaannila;

public class StrutsQuizMaster implements QuizMaster {

    @Override
public String popQuestion() {
return "Are you new to Struts?";
    }

}

SpringQuizMaster.java
----------------------
packagecom.vaannila;

public class SpringQuizMaster implements QuizMaster {

    @Override
public String popQuestion() {
return "Are you new to Spring?";
    }
}
We have a QuizMasterService class that displays the question to the user. TheQuizMasterService class holds reference to the QuizMaster.
QuizMasterService.java
-----------------------
packagecom.vaannila;

public class QuizMasterService {

privateQuizMasterquizMaster = new SpringQuizMaster();

public void askQuestion()
    {
System.out.println(quizMaster.popQuestion());
    }
}
Finally we create the QuizProgram class to conduct quiz.
QuizProgram.java
----------------
packagecom.vaannila;

public class QuizProgram {

public static void main(String[] args) {
QuizMasterServicequizMasterService = new QuizMasterService();
quizMasterService.askQuestion();
    }

}
As you can see it is pretty simple, here we create an instance of the QuizMasterService class and call the askQuestion() method. When you run the program as expected "Are you new to Spring?" gets printed in the console.
Let's have a look at the class diagram of this example. The green arrows indicate generalization and the blue arrows indicates association.
As you can see this architecture is tightly coupled. We create an instance of the QuizMaster in theQuizMasterService class in the following way.
privateQuizMasterquizMaster = new SpringQuizMaster();
To make our quiz master Struts genius we need to make modifications to the QuizMasterServiceclass like this.
privateQuizMasterquizMaster = new StrutsQuizMaster();
So it is tightly coupled. Now lets see how we can avoid this by using the Dependency Injectiondesign pattern. The Spring framework provides prowerful container to manage the components. The container is based on the Inversion of Control (IoC) principle and can be implemented by using the Dependency Injection (DI) design pattern. Here the component only needs to choose a way to accept the resources and the container will deliver the resource to the components.
In this example instead of we, directly creating an object of the QuizMaster bean in theQuizMasterService class, we make use of the container to do this job for us. Instead of hard coding any values we will allow the container to inject the required dependancies.
We can inject the dependancies using the setter or constructor injection. Here we will see how we can do this using the setter injection.
QuizMasterService.java
-----------------------
packagecom.vaannila;

public class QuizMasterService {

QuizMasterquizMaster;

public void setQuizMaster(QuizMasterquizMaster) {
this.quizMaster = quizMaster;
    }

public void askQuestion()
    {
System.out.println(quizMaster.popQuestion());
    }
}
The value for the QuizMaster will be set using the setQuizMaster() method. The QuizMaster object is never instantiated in the QuizMasterService class, but still we access it. Usually this will throw a NullPointerException, but here the container will instantiate the object for us, so it works fine.
After making all the changes, the class diagram of the example look like this.
The container comes into picture and it helps in injecting the dependancies.
The bean configuration is done in the beans.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">

<bean id="springQuizMaster" class="com.vaannila.SpringQuizMaster"></bean>
<bean id="strutsQuizMaster" class="com.vaannila.StrutsQuizMaster"></bean>
<bean id="quizMasterService" class="com.vaannila.QuizMasterService">
<property name="quizMaster">
<ref local="springQuizMaster"/>
</property>
</bean>

</beans>
We define each bean using the bean tag. The id attribute of the bean tag gives a logical name to the bean and the class attribute represents the actual bean class. The property tag is used to refer the property of the bean. To inject a bean using the setter injection you need to use the ref tag.
Here a reference of SpringQuizMaster is injected to the QuizMaster bean. When we execute this example, "Are you new to Spring?" gets printed in the console.
To make our QuizMaster ask questions related to Struts, the only change we need to do is, to change the bean reference in the ref tag.
<bean id="quizMasterService" class="com.vaannila.QuizMasterService">
<property name="quizMaster">
<ref local="strutsQuizMaster"/>
</property>
</bean>
In this way the Dependency Injection helps in reducing the coupling between the components.
To execute this example add the following jar files to the classpath.
antlr-runtime-3.0
commons-logging-1.0.4
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3

--------------------------------------------------------------------------------------------------------------------
Spring  Objective Type Question

Q 1 - Which of the following is correct about dependency injection?
A - It helps in decoupling application objects from each other.
Answer : A
Explanation
Dependency injection helps in decoupling application objects from each other.

Q 2 - What is bean scope?
A - Bean scope forces Spring to produce a new bean instance as per the scope defined.
Answer : A
Explanation
Bean scope instructs Spring Container to produce a new bean instance as per the scope defined.
 Hide Answer
Q 3 - What is request scope?
A - This scopes a bean definition to an HTTP request.
Answer : A
Explanation
request scope instructs Spring IoC container to create a instance per HTTP request.
 Hide Answer
Q 4 - What is no mode of autowiring?
A - Default setting which means no autowiring and you should use explicit bean reference for wiring.
Answer : A
Explanation
no mode of autowiring is the default mode which means no autowiring and you should use explicit bean reference for wiring.
 Hide Answer
Q 5 - What is Advice?
C - This is the actual action to be taken either before or after the method execution.
Answer : C
Explanation
Advice is the actual action to be taken either before or after the method execution.
 Hide Answer
Q 6 - Which of the following aspect implementation spring supports?
C - Both of above.
Answer : C
Explanation
Spring supports both XML Schema based and @AspectJ based aspect implementation.
 Show Answer
Q 7 - Core container has AOP as one of its module.
B - False
Answer : B
Explanation
AOP is not the part of spring core container.
 Hide Answer
Q 8 - Thread scoped bean is introduced in which version of spring framework.
C - 3.0
Answer : C
Explanation
Thread scoped bean is introduced in 3.0 version of spring framework.
 Show Answer
Q 9 - Which class is used to map a database row to a java object in spring?
B - RowMapper
Answer : B
Explanation
RowMapper class is used to map a database row to a java object in spring.
 Hide Answer
Q 10 - Which of the following class can be used to call Stored Procedures in spring?
D - SimpleJdbcCall
Answer : D
Explanation
SimpleJdbcCall class can be used to call Stored Procedures in spring.

------------------------------------------------------------------------------------------------------
Spring MVC Exception Handling








--------------------------------------------------------------------------------------------------------------------

Spring Hibernate Integration Example