在傳統MVC或者springboot框架中,經常要使用@Autowired註解注入Service或者Mapper接口,在controller層中注入service接口,在service層中注入其它的service接口或者mapper接口都是可以的,但是如果要在自己封裝的Utils工具類中或者非controller普通類中使用@Autowired註解注入Service或者Mapper接口,直接注入是不可能的,因爲Utils使用了靜態的方法,我們是無法直接使用非靜態接口的,當遇到這樣的問題,就要想辦法解決了。
有兩種方法解決這個問題,第一種是註解方式,第二種是xml配置方式,下面是在utils中使用@Autowired註解的方法:
第一種主要分爲三步:
1, 類方法名標註:@Component
2,使用@Autowired注入service或者mapper層
2, public static 類名 簡寫;如下的 public static TestUtils testUtils;
3,@PostConstruct註解,參照如下的init()方法
4,直接引用service層或者mapper:類名.service類名.方法名
@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();
}
}
第二種方法就是xml配置的方式,把init()方法上的@PostConstruct註解去掉,在spring-comtext.xml中配置以下bean
<bean id="testUtils" class="這裏寫utils類的包全路徑名" init-method="init"></bean>
非原創:原文鏈接http://www.tpyyes.com/a/javaweb/30.html根據自己的理解,加了一些總結