[Spring]: Notes

spring

08/09/2019


Spring docs

Spring

  • Simplify Java Enterprise Development -- simpler than J2EE
  • Lightweight development with Java POJOs(Plain-Old-Java-Objects)
  • Dependency injection that doesn't require hard-wiring

Spring Bean

  • Simply is a Java object
  • When Java objects are created by Spring Container, then Spring refers to them as Spring Beans

Spring Container

  • Primary functions:
    • Create and manage objects (Inversion of Control)
    • Inject object's dependencies (Dependency Injection)

Inversion of Control (IoC)

  • Design process of externalizing the construction & management of object
  • Outsource to an "object factory"

Dependency Injection

  • Inject all the dependences for an objects
    • dependency; helper object

Configuring Spring Container

  1. XML configuration(legacy)
  2. Java Annotations
  3. Java Source Code

Scope

  • Scope refers to the life cycle of a bean
    • How long does the bean live
    • How many instances are created
    • How is the bean shared

Types of scopes

  1. singleton (Default)
  • Spring Container creates only one shared instance of the bean by default
  • It is cached in memory
  • All requests for the bean will return a shared reference to the same bean
  • For example
JAVA
Player player1 = context.getBean("myPlayer", Player.class);
Player player2 = context.getBean("myPlayer", Player.class);
  • The same bean will be returned for player1 and player2
  • Following code returns true for singleton with the same memory location
JAVA
System.out.println(player1 == player2)
// Returns the same memory locations
System.out.println(player1)
System.out.println(player1)
  1. prototype
  • Creates a new bean instance for each container request
  • Above code will return false along with different allocated memory adderss
  1. request (for web apps)
  • Scoped to an HTTP web request
  1. session (for web apps)
  • Scoped to an HTTP web session
  1. global-session (for web apps)
  • Scoped to a global HTTP web session

Bean life cycle

  1. Container started

  2. Bean instantiated

  3. Dependencies injected

  4. Internal Spring processing

  5. Custom init method

    Custom code can be added during bean initialization

    We can call custom business logic methods

    Used to set up handles to resources(db, sockets, file, etc)

    Init method is executed after dependencies are injected

  6. (Bean is ready for use)

  7. Container is shutdown

  8. Custom destroy method

    Custom code can be added during bean destruction

    We can call custom business logic method Used to clean up handles to resources (db, sockets, files, etc)

    Destroy method is executed before the app actually stops

    Spring does not call destroy method for *prototype scoped beans


WRITTEN BY

Keeping a record