Spring 静态工具类如何注入service,dao层

3,462 阅读1分钟

我们经常要使用@Autowired注解注入Service或者Mapper接口,在service层中注入其它的service接口或者mapper接口都是可以的,但是如果我们要在我们自己封装的Utils工具类中或者非controller普通类中使用@Autowired注解注入Service或者Mapper接口,直接注入是不可能的,因为Utils使用了静态的方法,我们是无法直接使用非静态接口的,当我们遇到这样的问题,我们就要想办法解决了。

@Component   
public class TestUtils {  

@Autowired  
private ItemService itemService;  
@Autowired  
private ItemMapper itemMapper;  

public static TestUtils testUtils;  

@PostConstruct
public void init() {      
    testUtils = this;  
}   

//utils工具类中使用service和mapper接口的方法例子,用"testUtils.xxx.方法" 就可以了        
public ## static void test(Item record){  
    testUtils.itemMapper.insert(record);  
    testUtils.itemService.queryAll();  
    }
  1. 将 class DownLoadUtils 上添加 @Component 声明其为bean组件。
  2. 使用 @Autowired注入启动类。
  3. 在 DownLoadUtils 中声明一个 静态的私有变量 private static DownloadUtils downloadUtils;
  4. 添加共有的init方法,并用@PostConstruct声明在项目启动的时候进行执行该方法,也可以理解为在spring容器初始化的时候执行该方法。