MyBatis與Spring MVC結合時,使用DAO注入出現:Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required


錯誤源自使用了這個例子:http://www.yihaomen.com/article/java/336.htm,如果運行時會出現如下錯誤:

Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

以下是解決思路,參考:http://blog.csdn.net/xkhgnc_6666/article/details/52063713說的解決方法,分析如下:

1、從字面上意思理解是注入時導致了混亂,相同類型的Bean不知道是注入SqlSessionFactory還是SqlSessionTemplate。

2、可以使用@Qualifier注解和@Autowired注解通過指定哪一個真正的Bean將會被裝配來消除混亂,參考:http://wiki.jikexueyuan.com/project/spring/annotation-based-configuration/spring-qualifier-annotation.html,也就是具體指定使用上面的哪一個進行Bean注入。

具體解決代碼,在DAO中加入如下代碼:

    @Autowired(required = false)
    @Qualifier("sqlSessionFactory") 
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

還可以這樣寫:

    @Autowired(required = false)
    public void setSqlSessionFactory(
            @Qualifier("sqlSessionFactory")
            SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

效果都是一樣的。

 


免責聲明!

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



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