今天想使用單元測試類,存儲一些數據到mysql,可是,一直在報錯,org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'locationService' available
檢查了好久,實屬無奈找不出問題,試了一下手動構造注入javabean,奇跡的解決了這個問題。
單元測試具體寫法:
1.使用注解@Before 讀取dao層的xml配置文件,,注意,必須是dao層,否則找不到mybatis的會話工廠
2.需要使用構造注入service層的接口實現類后,程序才可以獲取mapper接口,,否則mapper接口實例后參數為null,會報空指針異常
3.構造注入的service層實現類 <bean> 必須寫在dao層的xml文件里,不可以在其他xml里單獨注入再獲取Javabean,否則會報錯誤創建bean。
當然,如果真的想寫在一個新的xml文件里,可以將新xml導入到dao層xml配置文件里。
dao層xml文件模板:

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd"> 9 <!-- 1.配置數據庫相關參數properties的屬性:${url} --> 10 <context:property-placeholder location="classpath:jdbc.properties"/> 11 12 <!-- 配置 數據源 --> 13 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 14 <!-- 驅動 --> 15 <property name="driverClassName" value="${jdbc.driverClassName}"/> 16 <!-- url --> 17 <property name="url" value="${jdbc.url}"/> 18 <!-- 用戶名 --> 19 <property name="username" value="${jdbc.username}"/> 20 <!-- 密碼 --> 21 <property name="password" value="${jdbc.password}"/> 22 </bean> 23 24 <!-- 配置 Mybatis的工廠 --> 25 <bean class="org.mybatis.spring.SqlSessionFactoryBean"> 26 <!-- 數據源 --> 27 <property name="dataSource" ref="dataSource"/> 28 <!-- 配置Mybatis的核心 配置文件所在位置 --> 29 <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> 30 <!-- 配置pojo別名 --> 31 <property name="typeAliasesPackage" value="cn.cen2guo.clinic.entity"/> 32 <!--當mapper中的接口文件與xml文件在同一個包下但是不在同一級時--> 33 <!--需要指定mapper 的xml文件路徑,如果在同一級則可不寫--> 34 <!-- 否則會報錯org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)--> 35 <property name="mapperLocations" value="classpath:cn/cen2guo/clinic/mapper/mapperXML/*.xml"/> 36 </bean> 37 38 <!--掃描mapper接口, 寫在此包下即可被掃描到 --> 39 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 40 <property name="basePackage" value="cn.cen2guo.clinic.mapper"/> 41 </bean> 42 43 44 <!-- 導入my_javabean.xml,用於自定義注冊構造注入的bean--> 45 <import resource="classpath:myxml/my_javabean.xml"/> 46 </beans>
自定義注冊bean的xml文件模板:

1 <?xml version="1.0" encoding="UTF-8" ?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!-- 位置信息服務接口--> 7 <bean id="locationService" class="cn.cen2guo.clinic.service.serviceImpl.LocationServiceImpl"/> 8 9 </beans>