• spring bean初始化和销毁


    spring bean的创建与消亡由spring容器进行管理,除了使用<bean><property/></bean>进行简单的属性配置之外,spring支持更人性化的方法

    • @PostConstruct @PreDestroy
    • xml的init-method和destroy-method
    • 实现InitializingBean和DisposableBean接口 
     1 public class BeanInitMethod implements InitializingBean, DisposableBean {
     2 
     3     private int step;
     4 
     5     public int getStep() {
     6         return step;
     7     }
     8 
     9     public void setStep(int step) {
    10         this.step = step;
    11     }
    12 
    13     @PostConstruct
    14     public void postConstruct() {
    15         System.out.println("initialized by annotation");
    16         step = 1;
    17     }
    18 
    19     @PreDestroy
    20     public void predestroy() {
    21         System.out.println("destroyed by annotation");
    22     }
    23 
    24     @Override
    25     public void afterPropertiesSet() throws Exception {
    26         System.out.println("initialized by interface");
    27         step = 2;
    28     }
    29 
    30     @Override
    31     public void destroy() throws Exception {
    32         System.out.println("destroyed by interface");
    33     }
    34 
    35     public void initFunc() {
    36         System.out.println("initialized by xml");
    37         step = 3;
    38     }
    39 
    40     public void destroyFunc() {
    41         System.out.println("destroyed by xml");
    42     }
    43 
    44     public static void main(String[] argv) {
    45         BeanInitMethod beanInitMethod;
    46         BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");
    47         beanInitMethod = (BeanInitMethod) beanFactory.getBean("initTestBean");
    48 
    49         System.out.println("step=" + beanInitMethod.getStep());
    50 
    51         System.out.println("program is done");
    52     }
    53 
    54 }

    对于“注解方式”还需要开启注解的支持,在上下文xml配置文件加入

    <context:annotation-config/>

    对于xml配置方式,则需要加入

    <bean id="initTestBean" class="edu.xhyzjiji.cn.spring.BeanInitMethod" init-method="initFunc" destroy-method="destroyFunc"/>

    当bean实例被创建时,会依据以下顺序执行初始化

    initialized by annotation
    initialized by interface
    initialized by xml
    step=3
    program is done
  • 相关阅读:
    angular4(2-1)angular脚手架引入第三方类库(jquery)
    angular4(1)angular脚手架
    vue-cli中的ESlint配置文件eslintrc.js详解
    咕着的题(慢慢补吧)
    图解Js event对象offsetX, clientX, pageX, screenX, layerX, x区别
    乐视手机H5项目总结
    解决ios下的微信打开的页面背景音乐无法自动播放
    html2canvas手机端模糊问题
    H5 canvas绘制出现模糊的问题
    hammer.js中文文档
  • 原文地址:https://www.cnblogs.com/xhyzjiji/p/6188592.html
Copyright © 2020-2023  润新知