1. 程式人生 > >Spring @Autowired註解在utils靜態工具類非controller普通類中使

Spring @Autowired註解在utils靜態工具類非controller普通類中使

在SpringMVC框架中,我們經常要使用@Autowired註解注入Service或者Mapper介面,我們也知道,在controller層中注入service介面,在service層中注入其它的service介面或者mapper介面都是可以的,但是如果我們要在我們自己封裝的Utils工具類中或者非controller普通類中使用@Autowired註解注入Service或者Mapper介面,直接注入是不可能的,因為Utils使用了靜態的方法,我們是無法直接使用非靜態介面的,當我們遇到這樣的問題,我們就要想辦法解決了。

我們有兩種方法解決這個問題,第一種是註解方式,第二種是xml配置方式,下面是我們在utils中使用@Autowired註解的方法:

@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();
    }
}

我們在init方法中使用以下註解就可以了,時間上這個init()的方法是可以自己隨便定義的,注意:inti()方法裡面不用寫任何東西,跟我這樣的就絕對ok了,不用看網上其他人瞎掰!

@PostConstruct

第二種方法就是xml配置的方式,也是很簡單的,我們可以把init()方法上的@PostConstruct註解去掉,在spring-comtext.xml中配置以下bean就好了,裡面什麼內容都不用寫,是不是很簡單?

<bean id="testUtils" class="這裡寫utils類的包全路徑名" init-method="init"></bean>

網上的其它資料都是扯淡,用我這兩種方式就絕對ok了。

來源網站:太平洋學習網,轉載請註明出處:http://www.tpyyes.com/a/javaweb/2016/1124/30.html