【Spring】 (4)bean的 声明周期内创建初始化和销毁方法

来源:互联网 发布:中学美工课教案 编辑:程序博客网 时间:2024/05/17 02:53
package com.example.demo_2_3;/** * Created by WangBin on 2017/4/12. * */public class BeanWayService {    public void init(){        System.err.println("BeanWayService 的初始化方法");    }    public BeanWayService(){        super();        System.err.println("BeanWayService 的 构造方法");    }    public void destroy(){        System.err.println("BeanWayService 的销毁方法");    }}



package com.example.demo_2_3;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;/** * Created by WangBin on 2017/4/12. * */public class JSR250WayService {    @PostConstruct //在构造函数执行完成之后执行    public void init(){        System.err.println("JSR250WayService的 初始化方法");    }    public JSR250WayService(){        super();        System.err.println("JSR250WayService 的 构造方法");    }    @PreDestroy// 在 bean销毁之前执行    public void destroy(){        System.err.println("JSR250WayService 的销毁方法");    }}


package com.example.demo_2_3;import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * Created by WangBin on 2017/4/12. * */public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class);        BeanWayService beanWayService =context.getBean(BeanWayService.class);        JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);        context.close();    }}


package com.example.demo_2_3;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;/** * Created by WangBin on 2017/4/12. * */@Configuration@ComponentScan("com.example.demo_2_3")public class PrePostConfig {    @Bean(initMethod = "init",destroyMethod = "destroy")// = 里写的是在 BeanWayService 里写的方法    BeanWayService beanWayService(){        return new BeanWayService();    }    @Bean//指定 JSR250WayService是一个bean    JSR250WayService jsr250WayService(){        return new JSR250WayService();    }}//先运行 构造方法  再运行 初始化方法 最后 执行销毁方法在bean销毁之前//JSR250 销毁比较快 编写方式比较简单



阅读全文
0 0
原创粉丝点击