用spring的InitializingBean的afterPropertiesSet來初始化


org.springframework.beans.factory包下有一個接口是InitializingBean 只有一個方法:

/**
  * Invoked by a BeanFactory after it has set all bean properties supplied
  * (and satisfied BeanFactoryAware and ApplicationContextAware).
  * <p>This method allows the bean instance to perform initialization only
  * possible when all bean properties have been set and to throw an
  * exception in the event of misconfiguration.
  * @throws Exception in the event of misconfiguration (such
  * as failure to set an essential property) or if initialization fails.
  */
 void afterPropertiesSet() throws Exception;

 

這個方法將在所有的屬性被初始化后調用。

但是會在init前調用。

但是主要的是如果是延遲加載的話,則馬上執行。

所以可以在類上加上注解:

import org.springframework.context.annotation.Lazy;

@Lazy(false)

這樣spring容器初始化的時候afterPropertiesSet就會被調用。

只需要實現InitializingBean接口就行。

如果代碼在這里初始化的話,半天都找不到。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM