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;
 
    }

 

posted @ 2018-11-07 21:19  随风而逝,只是飘零  阅读(6526)  评论(0编辑  收藏  举报