Spring框架中@PostConstruct注解詳解
初始化方式一:@PostConstruct注解
假設(shè)類UserController有個(gè)成員變量UserService被@Autowired修飾,那么UserService的注入是在UserController的構(gòu)造方法之后執(zhí)行的。
如果想在UserController對(duì)象生成時(shí)候完成某些初始化操作,而偏偏這些初始化操作又依賴于依賴注入的對(duì)象,那么就無法在構(gòu)造函數(shù)中實(shí)現(xiàn)(ps:spring啟動(dòng)時(shí)初始化異常),例如:
public class UserController {
@Autowired
private UserService userService;
public UserController() {
// 調(diào)用userService的自定義初始化方法,此時(shí)userService為null,報(bào)錯(cuò)
userService.userServiceInit();
}
}
因此,可以使用@PostConstruct注解來完成初始化,@PostConstruct注解的方法將會(huì)在UserService注入完成后被自動(dòng)調(diào)用。
public class UserController {
@Autowired
private UserService userService;
public UserController() {
}
// 初始化方法
@PostConstruct
public void init(){
userService.userServiceInit();
}
}
總結(jié):類初始化調(diào)用順序:
(1)構(gòu)造方法Constructor
(2)@Autowired
(3)@PostConstruct
初始化方式二:實(shí)現(xiàn)InitializingBean接口
除了采用注解完成初始化,也可以通過實(shí)現(xiàn)InitializingBean完成類的初始化
public class UserController implements InitializingBean {
@Autowired
private UserService userService;
public UserController() {
}
// 初始化方法
@Override
public void afterPropertiesSet() throws Exception {
userService.userServiceInit();
}
}
比較常見的如SqlSessionFactoryBean,它就是通過實(shí)現(xiàn)InitializingBean完成初始化的。
@Override
public void afterPropertiesSet() throws Exception {
// buildSqlSessionFactory()是完成初始化的核心方法,必須在構(gòu)造方法調(diào)用后執(zhí)行
this.sqlSessionFactory = buildSqlSessionFactory();
}補(bǔ)充:@PostConstruct注釋規(guī)則
- 除了攔截器這個(gè)特殊情況以外,其他情況都不允許有參數(shù),否則spring框架會(huì)報(bào)IllegalStateException;而且返回值要是void,但實(shí)際也可以有返回值,至少不會(huì)報(bào)錯(cuò),只會(huì)忽略
- 方法隨便你用什么權(quán)限來修飾,public、protected、private都可以,反正功能是由反射來實(shí)現(xiàn)
- 方法不可以是static的,但可以是final的
所以,綜上所述,在spring項(xiàng)目中,在一個(gè)bean的初始化過程中,方法執(zhí)行先后順序?yàn)?/p>
Constructor > @Autowired > @PostConstruct
先執(zhí)行完構(gòu)造方法,再注入依賴,最后執(zhí)行初始化操作,所以這個(gè)注解就避免了一些需要在構(gòu)造方法里使用依賴組件的尷尬。
總結(jié)
到此這篇關(guān)于Spring框架中@PostConstruct注解詳解的文章就介紹到這了,更多相關(guān)Spring @PostConstruct注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用idea開發(fā)javaWeb應(yīng)用程序的思路(實(shí)現(xiàn)用戶的增刪改查)
這篇文章主要介紹了使用idea開發(fā)javaWeb應(yīng)用程序的思路(實(shí)現(xiàn)用戶的增刪改查),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
java 實(shí)現(xiàn)下壓棧的操作(能動(dòng)態(tài)調(diào)整數(shù)組大小)
這篇文章主要介紹了java 實(shí)現(xiàn)下壓棧的操作(能動(dòng)態(tài)調(diào)整數(shù)組大小),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-02-02
java實(shí)現(xiàn)檢測(cè)是否字符串中包含中文
本文給大家分享了2個(gè)使用java檢測(cè)字符串中是否包含中文的代碼,都非常的實(shí)用,最后附上了各種字符的unicode編碼的范圍,方便我們以后使用正則進(jìn)行匹配檢測(cè)。2015-10-10
Spring的編程式事務(wù)TransactionTemplate的用法詳解
TransactionTemplate提供了一種在代碼中進(jìn)行編程式事務(wù)管理的方式,使開發(fā)人員能夠在方法級(jí)別定義事務(wù)的開始和結(jié)束點(diǎn),本文介紹了Spring框架中TransactionTemplate的用法,感興趣的朋友跟隨小編一起看看吧2023-07-07
簡單介紹Java網(wǎng)絡(luò)編程中的HTTP請(qǐng)求
這篇文章主要介紹了簡單介紹Java網(wǎng)絡(luò)編程中的HTTP請(qǐng)求,需要的朋友可以參考下2015-09-09

