Skip to content

Bean Scopes Bean Lifecycle

AyushiDamele edited this page Dec 9, 2020 · 2 revisions

Bean Scopes

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

Default Scope: Singleton

What Is a Singleton?

  • Spring Container creates only one 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

Explicitly Specify Bean Scope

<beans … >
    <bean  id="myCoach" 
		class="com.luv2code.springdemo.TrackCoach"
		scope="singleton"> 
		…    
	</bean>
</beans>

Additional Spring Bean Scopes Scope Description singleton Create a single shared instance of the bean. Default scope. prototype Creates a new bean instance for each container request. request Scoped to an HTTP web request. Only used for web apps. session Scoped to an HTTP web session. Only used for web apps. global-session Scoped to a global HTTP web session. Only used for web apps.

Prototype Scope Example Prototype scope: new object for each request

<beans … >
    <bean  id="myCoach"
		class="com.luv2code.springdemo.TrackCoach" 
		scope="prototype">
		…    
	</bean>
</beans>

Bean Lifecycle

1)Container Started 2)Dependencies Injected 3)Bean Instantiated 4)Internal Spring Processing 5)Your Custom Init Method 6)Bean Is Ready For Use Container Is Shutdown 7)Your Custom Destroy Method 8)Stop

Bean Lifecycle Methods / Hooks

  • You can add custom code during bean initialization * Calling custom business logic methods * Setting up handles to resources (db, sockets, file etc)
  • You can add custom code during bean destruction * Calling custom business logic method * Clean up handles to resources (db, sockets, files etc)

Init: method configuration

<beans … >    
	<bean  id="myCoach"
		class="com.luv2code.springdemo.TrackCoach"
		init-method="doMyStartupStuff">
		…    
	</bean>
</beans>

Destroy: method configuration

<beans … >
    <bean  id="myCoach"
		class="com.luv2code.springdemo.TrackCoach"
		init-method="doMyStartupStuff"
		destroy-method="doMyCleanupStuff">
		…    
	</bean>
</beans>

Development Process

  1. Define your methods for init and destroy
  2. Configure the method names in Spring config file

Java Annotations?

  • Special labels/markers added to Java classes
  • Provide meta-data about the class
  • Processed at compile time or run-time for special processing

Why Spring Configuration with Annotations?

  • XML configuration can be verbose
  • Configure your Spring beans with Annotations
  • Annotations minimizes the XML configuration

Development Process

  1. Enable component scanning in Spring config file
  2. Add the @Component Annotation to your Java classes
  3. Retrieve bean from Spring container

Step 1: Enable component scanning in Spring config file

<beans … > 
	<context:component-scan base-package="com.luv2code.springdemo" />
</beans>

Step 2: Add the @Component Annotation to your Java classes

@Component("thatSillyCoach") 
public class TennisCoach implements Coach { 
	@Override public String getDailyWorkout() {
		return "Practice your backhand volley"; 
	} 
}

Step 3: Retrieve bean from Spring container

Coach theCoach = context.getBean("thatSillyCoach", Coach.class);

Spring also supports Default Bean IDs • Default bean id: the class name, make first letter lower-case Class Name: TennisCoach Default Bean Id: tennisCoach If bean id is not specified while @Component Annotation is mentioned, it assumes default beanId.### Bean Scopes

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

Default Scope: Singleton

What Is a Singleton?

  • Spring Container creates only one 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

Explicitly Specify Bean Scope

<beans … >
    <bean  id="myCoach" 
		class="com.luv2code.springdemo.TrackCoach"
		scope="singleton"> 
		…    
	</bean>
</beans>

Additional Spring Bean Scopes Scope Description singleton Create a single shared instance of the bean. Default scope. prototype Creates a new bean instance for each container request. request Scoped to an HTTP web request. Only used for web apps. session Scoped to an HTTP web session. Only used for web apps. global-session Scoped to a global HTTP web session. Only used for web apps.

Prototype Scope Example Prototype scope: new object for each request

<beans … >
    <bean  id="myCoach"
		class="com.luv2code.springdemo.TrackCoach" 
		scope="prototype">
		…    
	</bean>
</beans>

Bean Lifecycle

  • 1)Container Started
  • 2)Dependencies Injected
  • 3)Bean Instantiated
  • 4)Internal Spring Processing
  • 5)Your Custom Init Method
  • 6)Bean Is Ready For Use Container Is Shutdown
  • 7)Your Custom Destroy Method
    1. Stop

Bean Lifecycle Methods / Hooks

• You can add custom code during bean initialization • Calling custom business logic methods • Setting up handles to resources (db, sockets, file etc) • You can add custom code during bean destruction • Calling custom business logic method • Clean up handles to resources (db, sockets, files etc)

Init: method configuration

<beans … >    
	<bean  id="myCoach"
		class="com.luv2code.springdemo.TrackCoach"
		init-method="doMyStartupStuff">
		…    
	</bean>
</beans>

Destroy: method configuration

<beans … >
    <bean  id="myCoach"
		class="com.luv2code.springdemo.TrackCoach"
		init-method="doMyStartupStuff"
		destroy-method="doMyCleanupStuff">
		…    
	</bean>
</beans>

Development Process

  1. Define your methods for init and destroy
  2. Configure the method names in Spring config file

Java Annotations?

• Special labels/markers added to Java classes • Provide meta-data about the class • Processed at compile time or run-time for special processing

Why Spring Configuration with Annotations?

  • XML configuration can be verbose
  • Configure your Spring beans with Annotations
  • Annotations minimizes the XML configuration

Development Process

      1. Enable component scanning in Spring config file
      1. Add the @Component Annotation to your Java classes
      1. Retrieve bean from Spring container

Step 1: Enable component scanning in Spring config file

<beans … > 
	<context:component-scan base-package="com.luv2code.springdemo" />
</beans>

Step 2: Add the @Component Annotation to your Java classes

@Component("thatSillyCoach") 
public class TennisCoach implements Coach { 
	@Override public String getDailyWorkout() {
		return "Practice your backhand volley"; 
	} 
}

Step 3: Retrieve bean from Spring container

Coach theCoach = context.getBean("thatSillyCoach", Coach.class);

Spring also supports Default Bean IDs • Default bean id: the class name, make first letter lower-case Class Name: TennisCoach Default Bean Id: tennisCoach If bean id is not specified while @Component Annotation is mentioned, it assumes default beanId.


Implementation using Annotations:

Explicitly Specify Bean Scope

@Component
@Scope("singleton")
public class TennisCoach implements Coach { 
    ... 
}

Init method configuration

@Component 
public class TennisCoach implements Coach { 
    @PostConstruct public void doMyStartupStuff() { … } 
    ... 
}

Destroy: method configuration

@Component public class TennisCoach implements Coach {
 @PreDestroy 
  public void doMyCleanupStuff() { … } 
  .. 
}


Development Process
1. Define your methods for init and destroy

2. Add annotations: @PostConstruct and @PreDestroy



Clone this wiki locally