9、spring注解学习(bean的生命周期)——使用JSR25:在bean的方法上用@PostConstruct和@PreDestroy注解

1、创建Bird类

@Component
public class Bird {
    public Bird() {
        System.out.println("Bird的构造方法执行了");
    }
    
    //对象构造并属性赋值后执行
    @PostConstruct
    public void PostConstruct() {
        System.out.println("Bird的PostConstruct方法执行了");
    }
    
    @PreDestroy
    public void destroy() {
        System.out.println("Bird的销毁方法执行了");
    }
}

2、在spring配置类中配置扫描Bird所在位置,使得Bird能够注入

/**
 * 测试bean的生命周期的配置
 */
@Configuration
@ComponentScan(value="com.atguigu")
public class MainConfigOfLifeCycle {

}

3、创建测试方法进行测试

    /*
     * 测试通过使用JSR25:在bean的方法上用@PostConstruct和@PreDestroy进而实现初始和销毁方法
     */
    @Test
    public void test03() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
        applicationContext.close();
    }

结果得到:

注意:

  单例对象:在容器创建时就注入,另外调用了初始化方法,容器关闭前执行了销毁方法
   多例对象:只有在获取的时候容器才给构造并调用初始化方法,另外容器不会调用多例对象的销毁方法

猜你喜欢

转载自www.cnblogs.com/lyh233/p/12441497.html
今日推荐