[Spring]: Notes
spring
08/09/2019
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
- XML configuration(legacy)
- Java Annotations
- 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
- 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 locationsSystem.out.println(player1)System.out.println(player1)- prototype
- Creates a new bean instance for each container request
- Above code will return false along with different allocated memory adderss
- request (for web apps)
- Scoped to an HTTP web request
- session (for web apps)
- Scoped to an HTTP web session
- global-session (for web apps)
- Scoped to a global HTTP web session
Bean life cycle
- Container started 
- Bean instantiated 
- Dependencies injected 
- Internal Spring processing 
- 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 
- (Bean is ready for use) 
- Container is shutdown 
- 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