Springboot中如果希望在Utils工具類中,使用到我們已經定義過的Dao層或者Service層Bean,可以如下編寫Utils類:
1. 使用@Component注解標記工具類StatisticsUtils:
2. 使用@Autowired(@Autowired和@Resource的區別不再介紹)注入我們需要的bean:
3. 在工具類中編寫init()函數,并使用@PostConstruct注解標記工具類,初始化Bean:
public class StatisticsUtils {@Autowiredprivate IdeaMemberDao ideaMemberDao;@Autowiredprivate ProjectMemberDao projectMemberDao;@Autowiredprivate IdeaMgrDao ideaMgrDao;@Autowiredprivate ProjectMgrDao projectMgrDao;public static StatisticsUtils statisticsUtils;@PostConstructpublic void init() {statisticsUtils = this;statisticsUtils.ideaMemberDao = this.ideaMemberDao;statisticsUtils.projectMemberDao = this.projectMemberDao;statisticsUtils.ideaMgrDao = this.ideaMgrDao;statisticsUtils.projectMgrDao = this.projectMgrDao;}
}
4. 然后我們在StatustucsUtils.getIdeaParticipateNum函數中,就可以使用到我們注入的ideaMemberDao了
? ?
public static Integer getIdeaParticipateNum(){return statisticsUtils.ideaMemberDao.NumOfIdea();}
---------------------?
作者:ObsessionLife?
來源:CSDN?
原文:https://blog.csdn.net/tjuyanming/article/details/78679978?
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!