Bean lifecycle
-> Container started
- Bean instantiated
- Dependencies injected
- Internal Spring Processing
- Your own custom init method (init-method)
- Bean is ready for use
- Your own custom destroy method (destroy-method)
-> Container is shut down
Prototype scopes
do not call the destroy method!
Init and destroy methods (XML)
<bean id="myFortuneService"
class="com.hvitoi.springdemo.HappyFortuneService">
</bean>
<bean id="myCoach"
class="com.hvitoi.springdemo.TrackCoach"
init-method="doMyStartup"
destroy-method="doMyCleanup">
<!-- set up constructor injection -->
<constructor-arg ref="myFortuneService" />
</bean>
package com.hvitoi.springdemo;
public class TrackCoach implements Coach {
private FortuneService fortuneService;
public TrackCoach() {}
public TrackCoach(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}
@Override
public String getDailyWorkout() {
return "Run a hard 5k";
}
@Override
public String getDailyFortune() {
return "Just Do It: " + fortuneService.getFortune();
}
// init method
public void doMyStartup() {
System.out.println("TrackCoach: inside doMyStartup");
}
// destroy method
public void doMyCleanup() {
System.out.println("TrackCoach: inside doMyCleanup");
}
}
Init and destroy methods (Annotations)
@PostConstruct
and@PreDestroy
are used- The methods can have any access modifier
- Void is the most commonly used return type. Although any is accepted
- Method can have any name
-
Method should be no-arg
-
for java 9+, the annotation classes must be downloaded and imported into the project
javax.annotation-api-1.3.2.jar
- https://search.maven.org/remotecontent?filepath=javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar
@PostConstruct
public void doMyStartup() {
System.out.println(">> TennisCoach: inside of doMyStartup()");
}
@PreDestroy // Never called for prototype scopes!
public void doMyCleanup() {
System.out.println(">> TennisCoach: inside of doMyCleanup()");
}