方法:通过@Bean指定init-method和destroy-method;
注:单实例和原型模式对象的创建时间和初始化销毁的时间顺序不同。
一、单实例模式
1、创建Car实例对象,并创建初始化和销毁方法
package com.atguigu.bean;
import org.springframework.stereotype.Component;
@Component
public class Car {
public Car(){
System.out.println("car constructor...");
}
public void init(){
System.out.println("car ... init...");
}
public void detory(){
System.out.println("car ... detory...");
}
}
2、配置类
@Bean注解中指定初始化和销毁方法
@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {
@Bean(initMethod="init",destroyMethod="detory")
public Car car(){
return new Car();
}
}
3、测试
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.atguigu.config.MainConfigOfLifeCycle;
public class IOCTest_LifeCycle {
@Test
public void test01(){
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//关闭容器
applicationContext.close();
}
}
结果:
二、多实例模式
1、创建Car.java,并创建init()和detory()方法
import org.springframework.stereotype.Component;
@Component
public class Car {
public Car(){
System.out.println("car constructor...");
}
public void init(){
System.out.println("car ... init...");
}
public void detory(){
System.out.println("car ... detory...");
}
}
2、配置类
@Bean注解中指定初始化和销毁方法,并指定为原型模式Scope("prototype")
@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {
@Scope("prototype")
@Bean(initMethod="init",destroyMethod="detory")
public Car car(){
return new Car();
}
}
测试:
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.atguigu.config.MainConfigOfLifeCycle;
public class IOCTest_LifeCycle {
@Test
public void test01(){
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
applicationContext.getBean("car");
//关闭容器
applicationContext.close();
}
}
结果:
说明:原型模式时容器创建完成后才创建对象和初始化对象
且不会调用销毁方法。