Spring建構函式注入,無法注入的問題
阿新 • • 發佈:2019-02-18
手動配置bean主要與web中的一個配置目錄相關
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-mybatis.xml
</param-value>
</context-param>
上面配置的作用是:<!-- 指定Spring Bean的配置檔案所在目錄。預設配置在WEB-INF目錄下 -->
<param-value>的內容可以是1個,也可以是多個,中間用逗號隔開
之所以自己在spring-mvc.xml中配置bean一直無法正常注入,就是因為這裡的
<param-value>中沒有spring-mvc.xml,自己嘗試在spring-mybatis.xml中配置,可正常注入,因此就翻看web.xml的配置。
嘗試修改SpringMVC的開啟順序,<load-on-startup>1</load-on-startup>,將1改為0,還是不行。
然後嘗試,將spring-mvc.xml也加入到contextConfigLocation配置中,就可以正常注入了。
如下
<context-param>
<param-name>contextConfigLocation</param-name >
<param-value>
classpath:spring-mybatis.xml, classpath:spring-mvc.xml
</param-value>
</context-param>
報錯資訊如下:
ERROR] [org.springframework.web.context.ContextLoader] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskJob': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [pubinfo.controller.TestCons]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(mappedName=, shareable=true, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskJob': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [pubinfo.controller.TestCons]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(mappedName=, shareable=true, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}