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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM