1. bean life cycle
bean creation initialization destroy
Construction (object creation):
Single instance: create an object when the container starts;
Multi instance: create an object every time you get it;
Initialization:
The object is created and assigned. Call the initialization method.
Destruction:
Single instance, when the container is closed;
Multi instance: the container does not manage the bean, and the container calls the destroy method.
2. User defined initialization method and destruction method
2.1. Specify initmethod and destroymethod through @ Bean
- Mainconfiglife cycle class
@Configuration public class MainConfigLifeCycle { @Bean(initMethod = "init", destroyMethod = "destroy") public Car car() { return new Car(); } }
- Class Car
public class Car { public Car() { System.out.println("new car"); } public void init() { System.out.println("car init"); } public void destroy() { System.out.println("car destroy"); } }
- Ioctest life cycle class
@Test public void test1() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class); System.out.println("Container initialization"); context.close(); }
2.2. By enabling the bean to implement the InitializingBean interface (define the initialization interface), the DisposableBean interface (destroy interface)
- Class Cat
@Component public class Cat implements InitializingBean,DisposableBean { public Cat() { System.out.println("new cat"); } public void destroy() throws Exception { System.out.println("cat destroy"); } public void afterPropertiesSet() throws Exception { System.out.println("cat afterPropertiesSet"); } }
- Mainconfiglife cycle class
@ComponentScan("com.dav.bean") @Configuration public class MainConfigLifeCycle { }
- Ioctest life cycle class
@Test public void test1() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class); System.out.println("Container initialization"); context.close(); }
2.3. JSR250 annotation using JAVA
@PostConstruct: execute initialization method after bean creation and property assignment;
@PreDestroy: inform us to clean up the bean before the container destroys it;
- Class Dog
@Component public class Dog { public Dog() { System.out.println("new dog"); } @PostConstruct public void init() { System.out.println("dog @PostConstruct"); } @PreDestroy public void destroy() { System.out.println("dog @PreDestroy"); } }
- Mainconfiglife cycle class
@ComponentScan("com.dav.bean") @Configuration public class MainConfigLifeCycle { }
- Ioctest life cycle class
@Test public void test1() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class); System.out.println("Container initialization"); context.close(); }