• Springboot bean初始化方法InitializingBean


    spring boot InitializingBean接口使用总结

    • 被spring管理
    • 实现InitializingBean接口 
    • 重写afterPropertiesSet方法

    InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。

    代码入下

    @Component
    @PropertySource("classpath:common/testFile.properties")
    //注意这个实现InitializingBean接口,重写afterPropertiesSet方法
    public class Test implements InitializingBean { private static final Logger logger = LoggerFactory.getLogger(Test.class); @Value("${hdfs.user.root}") private String hdfs; @Override public void afterPropertiesSet() throws Exception { System.out.println("init"); } }

    测试代码,测试每次调用这个方法都会重新初始化,还是只初始化一次

    @Component
    @RestController
    public class Hello {
    
        private static final Logger logger = LoggerFactory.getLogger(Hello.class);
        
        @Autowired
        private Test test;
    
        @RequestMapping("/get")
        public void get() {
            System.out.println("从别的配置文件中读取"+test.getHdfs());
        }
    }

    测试结果,只对bean进行了一次初始化,以后并不会在调用它了

    这说明在spring初始化bean的时候,如果bean实现了InitializingBean接口,会自动调用afterPropertiesSet方法。

    总结:

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

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

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

  • 相关阅读:
    Spring boot 整合 Mybatis + Thymeleaf开发web(一)
    JAVA截取字符串的几种方式
    【转】JAVA异常报错大全
    Linux中允许远程用户登录访问mysql的方法
    Ubuntu系统下将默认的python2.7升级到3.5
    Ubuntu+Django+Nginx+uWSGI+Mysql搭建Python Web服务器
    python将数据写入excel代码,python与office交互
    pyqt4桌面软件各种画布组合结构实例
    python之pyqt4的简单窗口布局以及信号和槽(上代码)
    python 005 正则表达式
  • 原文地址:https://www.cnblogs.com/erlou96/p/13724154.html
Copyright © 2020-2023  润新知