今天想使用单元测试类,存储一些数据到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层实现类 必须写在dao层的xml文件里,不可以在其他xml里单独注入再获取Javabean,否则会报错误创建bean。
当然,如果真的想写在一个新的xml文件里,可以将新xml导入到dao层xml配置文件里。
dao层xml文件模板:
1 <?xml version="1.0" encoding="UTF-8"?>
2
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/beans6 http://www.springframework.org/schema/beans/spring-beans.xsd7 http://www.springframework.org/schema/context8 http://www.springframework.org/schema/context/spring-context.xsd">
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
View Code
自定义注册bean的xml文件模板:
1 <?xml version="1.0" encoding="UTF-8"?>
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans5 http://www.springframework.org/schema/beans/spring-beans.xsd">
6
7
8
9
View Code