一、afterPropertiesSet作用
在Spring中,我們經常會使用到afterPropertiesSet這個方法,它屬於InitializingBean介面,在Bean初始化之後執行。其主要作用是對Bean的屬性進行校驗和初始化。在Spring中,對於Bean的屬性,通常會配合註解或者xml配置方式進行注入或者賦值,而且屬性賦值或注入是在對象實例化之後進行的,所以我們無法在構造方法中進行對Bean屬性值的校驗。afterPropertiesSet就是解決了這個問題,它提供了一個回調方法,讓我們在Bean屬性賦值後對值進行校驗和初始化。
二、afterPropertiesSet方法作用
在Spring中,afterPropertiesSet是一個被回調的方法,也是Bean初始化之後進行校驗和初始化的方法。當Bean的屬性屬性值賦完之後,Spring會自動調用該方法,從而完成屬性值的校驗和初始化。和自定義方法不同的是,afterPropertiesSet方法可以在Bean對象被使用前,自動對Bean對象的屬性對其進行初始化操作。這是因為該方法是在Bean實例化後,所有屬性值賦值之後,其他初始化操作之前調用的。
三、afterPropertiesSet方法
afterPropertiesSet方法需要實現InitializingBean介面,需要在類中重寫該方法,實現初始化的操作。
<bean id="redisClient" class="com.xxx.RedisClient" init-method="init"> <property name="host" value="localhost"/> <property name="port" value="6379"/> <property name="password" value="password"/> </bean> public class RedisClient implements InitializingBean{ private String host; private int port; private String password; private Jedis jedis; //初始化方法 public void init() { jedis = new Jedis(host,port); jedis.auth(password); } //重寫afterPropertiesSet方法 @Override public void afterPropertiesSet() throws Exception { if (StringUtils.isEmpty(host)) { throw new IllegalArgumentException("host property not set!"); } if (port <= 0) { throw new IllegalArgumentException("port property not set!"); } } //getter/setter省略 }
四、afterPropertiesSet不執行
如果在Spring XML文件中沒有配置BeanPostProcessor進行對Bean進行代理,那麼afterPropertiesSet方法就不會被執行。此外,還有一種情況,就是Bean中沒有實現InitializingBean介面,也就是沒有afterPropertiesSet方法,那麼也會導致此方法不會被執行。
五、afterPropertiesSet執行順序
在一個Bean消費的時候,Spring管理的Bean中所有的屬性,都會在Bean的構造方法調用之後進行賦值,然後最後執行afterPropertiesSet回調方法進行Bean的初始化。具體順序如下:
- 1、實例化Bean對象
- 2、設置Bean對象的屬性
- 3、檢測是否實現了BeanPostProcessor介面,如果實現了,進行後置處理
- 4、檢測是否實現了InitializingBean介面,如果實現了,則調用afterPropertiesSet方法
- 5、BeanPostProcessor介面postProcessBeforeInitialization方法
- 6、調用默認的init-method方法
- 7、BeanPostProcessor介面postProcessAfterInitialization方法
六、afterPropertiesSet方法執行順序
如果一個類實現了多個BeanPostProcessor後置處理介面以及InitializingBean介面,那麼它們的執行順序發生以下變化:
1、多個BeanPostProcessor介面的實現類的先後順序不確定。
2、BeanPostProcessor介面的實現類的postProcessBeforeInitialization方法會在InitializingBean介面的afterPropertiesSet方法之前執行,postProcessAfterInitialization方法會在afterPropertiesSet方法之後執行。
七、afterPropertiesSet會執行多少遍
afterPropertiesSet方法僅在Bean初始化之後執行,因此它只會執行一次。
八、afterPropertiesSet和Autowired
在Spring中,容器在自動注入之後會調用afterPropertiesSet方法,因此我們可以在afterPropertiesSet方法中處理注入的依賴項。如下我們來看個例子:
@Component public class ExampleBean implements InitializingBean{ private SomeService someService; @Autowired public void setSomeService(SomeService someService) { this.someService = someService; } //重寫afterPropertiesSet方法 @Override public void afterPropertiesSet() throws Exception { if (this.someService == null) { throw new IllegalArgumentException("someService property null!"); } } //其他方法省略 }
在上述代碼中,如果someService依賴項未正確注入,將拋出異常,從而保證了Bean初始化的必要條件。
原創文章,作者:RUKWQ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/324737.html