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