解決非controller使用@Autowired注解注入報錯為java.lang.NullPointerException問題


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

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

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

 


免責聲明!

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



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