spring Annotation How to Specify InitMethod and DestroyMethod for bean
- 2021-12-12 08:41:07
- OfStack
Directory spring annotation specifies InitMethod and DestroyMethod for bean. Below is the specific code. Note initMethod and destroyMethod in @ Bean
The spring annotation specifies InitMethod and DestroyMethod for bean
/**
* Specifies the formed init Methods and destroy Several methods of
* 1 In the configuration class @Bean(initMethod = "init",destroyMethod = "destory") Annotation Specification
* 2 : Implementation InitializingBean Interface overrides its afterPropertiesSet Method, implementing DisposableBean Interface rewriting destroy Method
* 3 : Use java Adj. JSR250 In the specification @PostConstruct Marked in init Methodologically, @PreDestroy Marked in destroy On the annotation
*/
It should be noted that:
Single instance bean: Create an object when the container starts Multi-instance bean: Create an object every time you get itInitialization:
Object creation is completed, assignment is completed, and initialization method is calledDestroy:
Single instance: Called when the container is closed Multiple instances: The container will not be destroyed, and the destruction method can only be called manually
The following is the specific code
Car.java
public class Car {
public Car() {
System.out.println("Car's Constructor..");
}
public void init(){
System.out.println("Car's Init...");
}
public void destory(){
System.out.println("Car's Destroy...");
}
}
Configuration class
@Bean(initMethod = "init",destroyMethod = "destory")
public Car car(){
return new Car();
}
Note initMethod and destroyMethod in @ Bean
@Configuration
public class AppConfig {
@Bean(initMethod = "init")
public Foo foo() {
return new Foo();
}
@Bean(destroyMethod = "cleanup")
public Bar bar() {
return new Bar();
}
}
There are no parentheses after initMethod and destroyMethod in the above code.
Remember never to put brackets.