方法:使用JSR250;
在初始化方法上面添加:@PostConstruct注解;在销毁方法上面添加: @PreDestroy注解;
@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy:在容器销毁bean之前通知我们进行清理工作
注:单实例时容器关闭的时候会销毁对象;多实例时容器不会管理这个bean,即容器不会调用销毁方法;
一、创建Bean类
用@Component标注,可以被扫描完成自动装配
在初始化方法上面添加:@PostConstruct注解;在销毁方法上面添加: @PreDestroy注解;
@PostConstruct和@PreDestroy都是Javax包中的注解。
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class Dog {
public Dog(){
System.out.println("dog constructor...");
}
//对象创建并赋值之后调用
@PostConstruct
public void init(){
System.out.println("Dog....@PostConstruct...");
}
//容器移除对象之前
@PreDestroy
public void detory(){
System.out.println("Dog....@PreDestroy...");
}
}
二、配置类
标注@ComponentScan("com.atguigu.bean"),表示扫描该包下所有有@Controller,@Service,@Repository,@Component注解的类
@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {
@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();
}
}
结果:
说明:添加了注解后,容器自动调用初始化和销毁的方法。