美文网首页
Spring容器初始化和销毁定义操作

Spring容器初始化和销毁定义操作

作者: Snow_DZG | 来源:发表于2016-08-09 10:17 被阅读91次

Spring容器初始化和销毁定义操作

第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
/**
 * 服务初始化
 */
@PostConstruct
public void init() {
    this.register(); // 注册
    this.leader(); // 选主
    this.dictionary(); // 字典
}

@PreDestroy
public void destory() {
    logger.info("Service Stopped");
}
第二种:通过 在xml中定义init-method 和 destory-method方法

applicationContext.xml配置文件:

<bean id="XXX" class="com.XXX" scope="singleton"  init-method="init"  destroy-method="cleanUp"></bean>

对应实体类需要对应有这2个方法

TIP:

AbstractApplicationContext  context = new  ClassPathXmlApplicationContext("applicationContext.xml");
context.registerShutdownHook();  

context.registerShutdownHook(); 是一个钩子方法,当jvm关闭退出的时候会调用这个钩子方法,  
在设计模式之 模板模式中 通过在抽象类中定义这样的钩子方法由实现类进行实现,
这里的实现类是AbstractApplicationContext,这是spring 容器优雅关闭的方法
第三种: 通过bean实现InitializingBean和 DisposableBean接口

实体类实现接口

public class XXX implements InitializingBean,DisposableBean{  

    @Override  
    public void destroy() throws Exception {  
        // TODO Auto-generated method stub  
        System.out.println("我是销毁操作");  
    }  
  
    @Override  
    public void afterPropertiesSet() throws Exception {  
        // TODO Auto-generated method stub  
        System.out.println("我是初始化操作");  
    }  
}  

相关文章

网友评论

      本文标题:Spring容器初始化和销毁定义操作

      本文链接:https://www.haomeiwen.com/subject/tqxdsttx.html