• Spring初始化Bean和销毁Bean时做处理


    在配置bean实例时,xml中设置init和destroy方法:

    <bean class="com.test.Demo" init-method="init" destroy-method="destroy"/>
    public class Demo{
        public void init() {
            System.out.println("Demo.class init method ...");
        }
        public void destroy() {
            System.out.println("Demo.class destroy method ...");
        }
    }

    bean实现BeanPostProcessor接口,实现接口中的postProcessBeforeInitialization(初始化之前执行),postProcessAfterInitialization(bean初始化之后执行)

    public class Demo implements BeanPostProcessor {  
       @Override  
       public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
           System.out.println("对象" + beanName + "开始初始化");  
           return bean;  
       }  
    
       @Override  
       public Object postProcessAfterInitialization(Object bean, String beanName)  throws BeansException {  
           System.out.println("对象" + beanName + "初试化完成");  
           return bean;  
       }  
    }
    <bean id="demo" class="com.test.Demo" />

    bean实现InitializingBean和DisposableBean接口

    public class Demo implements InitializingBean, DisposableBean {
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("Demo.class init method ...");
        }
    
        @Override
        public void destroy() throws Exception {
            System.out.println("Demo.class destroy method ...");
        }
    }
    <bean id="demo" class="com.test.Demo" />

    使用@PostConstruct和@PreDestroy注解

    @Component
    public class Demo {
        @PostConstruct
        public void init() {
            System.out.println("Demo .class init method ...");
        }
    
        @PreDestroy
        public void destroy() {
            System.out.println("Demo .class destroymethod ...");
        }
    }
  • 相关阅读:
    springboot集成thymeleaf中不能返回页面,只返回字符串
    MySql 视图
    边缘计算网关的作用
    什么是物联网网关?它有什么功能?
    RS232串口跟RS485串口有什么优缺点
    4G DTU在油田远程监控中的应用
    远程IO模块有何用途
    Spring5快乐教程(一)Spring概述
    vue水印-第一种方法
    js获取随机打乱的数组
  • 原文地址:https://www.cnblogs.com/DreamFather/p/14592042.html
Copyright © 2020-2023  润新知