1. 程式人生 > >Springboot中如何在Utils類中使用@Autowired注入bean

Springboot中如何在Utils類中使用@Autowired注入bean

Springboot中如果希望在Utils工具類中,使用到我們已經定義過的Dao層或者Service層Bean,可以如下編寫Utils類:

1. 使用@Component註解標記工具類StatisticsUtils:

2. 使用@Autowired(@Autowired和@Resource的區別不再介紹)注入我們需要的bean:

3. 在工具類中編寫init()函式,並使用@PostConstruct註解標記工具類,初始化Bean:

public class StatisticsUtils {
 
    @Autowired
    private IdeaMemberDao ideaMemberDao;
    @Autowired
    
private ProjectMemberDao projectMemberDao; @Autowired private IdeaMgrDao ideaMgrDao; @Autowired private ProjectMgrDao projectMgrDao; public static StatisticsUtils statisticsUtils; @PostConstruct public void init() { statisticsUtils = this; statisticsUtils.ideaMemberDao
= this.ideaMemberDao; statisticsUtils.projectMemberDao = this.projectMemberDao; statisticsUtils.ideaMgrDao = this.ideaMgrDao; statisticsUtils.projectMgrDao = this.projectMgrDao; }