zoukankan      html  css  js  c++  java
  • spring中InitializingBean和@Bean的初始化,bean初始化

    InitializingBean接口听过bean的初始化防范,只包括afterPropertiesSet方法,凡是继承接口的类,在初始化bean的时候都会执行该方法。
    
    import org.springframework.beans.factory.InitializingBean;
    public class TestInitializingBean implements InitializingBean{
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("ceshi InitializingBean");        
        }
        public void testInit(){
            System.out.println("ceshi init-method");        
        }
    }

    bean的InitMethod和DestroyMethod

    1:在配置类中 @Bean(initMethod = "init",destroyMethod = "destory")注解指定
    2:实现InitializingBean重写其afterPropertiesSet方法,重写DisposableBean重写destroy方法
    3:利用java的JSR250规范中的@PostConstruct标注在init方法上,@PreDestroy标注在destroy注解上

    需要注意:

    单实例bean,容器启动时创建 对象

    多实例bean,没次获取时创建对象

    初始化:对象创建完成,复制完成,调用初始化方法

    销毁:单实例,容器关闭时调用,多实例,容器不会销毁,只能手动调用销毁方法

    类:


    public class Car {

    public Car() {
    System.out.println("Car's Constructor..");
    }

    public void init(){
    System.out.println("Car's Init...");
    }

    public void destory(){
    System.out.println("Car's Destroy...");
    }

    }

    配置类:

    @Bean(initMethod = "init",destroyMethod = "destory") 

    public Car car(){

    return new Car(); 

    }

    总结:

    1、Spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中通过init-method指定,两种方式可以同时使用。

    2、实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率要高一点,但是init-method方式消除了对spring的依赖。

    3、如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。



  • 相关阅读:
    python assert断言函数
    Python中错误之 TypeError: object() takes no parameters、TypeError: this constructor takes no arguments
    python 3.5构建WINDOWS推送服务
    Python调用(运行)外部程序
    sqlalchemy相关知识
    利用rabbit_mq队列消息实现对一组主机进行命令下发
    Centos 下安装Zabbix Linux 客户端
    Lynis 2.2.0 :面向Linux系统的安全审查和扫描工具
    防暴力破解 Fail2Ban之python
    linux服务器被攻击处理过程
  • 原文地址:https://www.cnblogs.com/lalalazar/p/12509904.html
Copyright © 2011-2022 走看看