解決非controller使用@Autowired注解注入為null問題


在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM