• 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指定的方法。

  • 相关阅读:
    穷举法和搜索法的统计三角形
    2015.5.21 Core Java Volume 1
    我喜欢出发
    MeshLab中画面在前面加个f的代码
    【axel帮助代码】为了在单位正方形里面画一个洞 ,网上获取了此代码。
    uniapp 发起网络请求
    qt 取进程列表,读写内存, 写字节集
    qt 注册热键
    qt 获取窗口句柄的线程id和进程id GetWindowThreadProcessId
    qt 向窗口发送消息,键盘输入事件
  • 原文地址:https://www.cnblogs.com/erlou96/p/16878451.html
Copyright © 2020-2023  润新知