[Spring Boot实战系列] - No.4 Spring boot 中如何在Utils类中使用@Autowired注入bean
2017-11-30 19:49
886 查看
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;
}
}4. 然后我们在StatustucsUtils.getIdeaParticipateNum函数中,就可以使用到我们注入的ideaMemberDao了
public static Integer getIdeaParticipateNum(){
return statisticsUtils.ideaMemberDao.NumOfIdea();
}
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;
}
}4. 然后我们在StatustucsUtils.getIdeaParticipateNum函数中,就可以使用到我们注入的ideaMemberDao了
public static Integer getIdeaParticipateNum(){
return statisticsUtils.ideaMemberDao.NumOfIdea();
}
相关文章推荐
- Spring系列【04】应用@Autowired注解实现Bean的注入
- 在搭建spring boot环境时,碰到总是不能Autowired,总是提示需要注入bean文件
- spring 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- Action中如何通过@Autowired自动注入spring bean ?
- 在搭建spring boot环境时,碰到总是不能Autowired,总是提示需要注入bean文件
- springboot使用aop拦截controller干一些事导致service们@Autowired全部注入失败
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- 如何解决SpringBoot JpaRepository @Autowired 没法自动注入的问题
- Spring对于Bean的依赖注入:@Autowired @Inject @Resource
- Spring-test使用JUnit时,测试类autowired报错,create bean error
- Spring整理系列(10)——@Autowired自动装配、结合@Qualifier过滤及与JSR-250@Resource注解、JSR-330@Inject注解的区别、@Named使用
- Spring Boot系列四 Spring @Value 属性注入使用总结一
- 【spring】BeanPostProcessor使用场景之@Autowired
- Spring Boot @Autowired 没法自动注入的问题
- 关于Struts在Spring中使用autowired 自动注入的问题
- Spring Boot异常:BeanCreationException:Injection of autowired dependencies failed;
- Spring用@Autowired注入Map类型Bean时报错解决
- 如何使用spring的autowire为servlet注入Bean
- Spring Boot异常:BeanCreationException:Injection of autowired dependencies failed;