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

Springboot中如果希望在Utils工具类中,使用到我们已经定义过的Dao层或者Service层Bean,可以如下编写Utils类:

1. 使用@Component注解标记工具类StatisticsUtils:

2. 使用@Autowired(@Autowired和@Resource的区别不再介绍)注入我们需要的bean:

3. 在工具类中编写init()函数,并使用@PostConstruct注解标记工具类,初始化Bean:

1public class StatisticsUtils { 2 3 @Autowired 4 private IdeaMemberDao ideaMemberDao; 5 @Autowired 6 private ProjectMemberDao projectMemberDao; 7 @Autowired 8 private IdeaMgrDao ideaMgrDao; 9 @Autowired 10 private ProjectMgrDao projectMgrDao; 11 12 public static StatisticsUtils statisticsUtils; 13 14 @PostConstruct 15 public void init() { 16 statisticsUtils = this; 17 statisticsUtils.ideaMemberDao = this.ideaMemberDao; 18 statisticsUtils.projectMemberDao = this.projectMemberDao; 19 statisticsUtils.ideaMgrDao = this.ideaMgrDao; 20 statisticsUtils.projectMgrDao = this.projectMgrDao; 21 22 }
点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Spring Boot的@Service和@Autowired和@ComponentScan注解

SpringBoot的@Service和@Autowired和@ComponentScan注解SpringBoot项目的Bean装配默认规则是根据Application类(SpringBoot项目入口类)所在的包位置从上往下扫描,即只扫描该类所在的包及其子包。1.如果需要扫描其上层包中的类,则将其移动到其上层包中2.使用@ComponentSc

Spring 学习笔记(三):Spring Bean

1Bean配置Spring可以看做是一个管理Bean的工厂,开发者需要将Bean配置在XML或者Properties配置文件中。实际开发中常使用XML的格式,其中<bean中的属性或子元素如下:id:Bean在BeanFactory中的唯一标识,在代码中通过BeanFac

spring3.x注解自动注入

一、各种注解方式1.@Autowired注解(不推荐使用,建议使用@Resource)@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。@Autowired的标注位置不同,它们都会在Spring在初始化这个bean时,自动装配这个属性。要使@Autowired能够工作,还需要在配置文件中加入以下Xml代码

Spring 4.3 的新功能和增强

核心容器改进核心容器额外提供了更丰富的元数据来改进编程。默认Java8的方法检测为bean属性的getter/setter方法。如果目标bean只定义了一个构造函数,则它无需要指定@Autowired注解@Configuration类支持构造函数注入。任何SpEL

SpringMvc中@resource和@autowired区别

在java代码中使用@Autowired或@Resource注解方式进行装配这两个注解的区别是:@Autowired默认按类型装配,@Resource(https://my.oschina.net/u/929718)默认按名称装配,当找不到与名称匹配的bean才会按类型装配。如果我们想使用按名称装