mybatis动态代理mapper(interface),然后用@Res..注入一直报错,然后无奈用了配置文件,
在service层用get/set方法来做,发现这个MAPPER还是空的!!
@Service("testService")
public class TestServiceImpl implements TestService{
private TestMapper testMapper;
public TestMapper getTestMapper() {
return testMapper;
}
public void setTestMapper(TestMapper testMapper) {
this.testMapper = testMapper;
}
@Transactional
@Override
public Object tset1(){
TestMapper mapper = ApplicationContextFactory.getBean("testMapper", TestMapper.class);
mapper.insertOne();
throw new RuntimeException("test");
}
}
如上,但是ApplicationContextFactory.getBean又可以取到并且操作,扫描包应是没问题的,不然应该会报错吧
@Autowired
private TestMapper testMapper;
你的类变量testMapper只是声明了bean,但是并没有注入到这个类里面来。
这段代码看起来并没有错误。不过有可能是因为没有截图完。
@Autowired/@resource两个注解都是可以的。
private TestMapper testMapper;
你mapper加上
@Component("testmapper")
@Mapper
public interface TestMapper{
}
用@Resource注入试一试
@Resource(name="testmapper")
private TestMapper testMapper;
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.zcloudMVC.mapper.TestMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, mappedName=, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}
这是用注解报的错
mapper 相当于hibernate的dao 组件了,需要被spring扫描到,检查一下spring的配置文件:
....
<bean name="testService" class="com.zcloudMVC.service.impl.TestServiceImpl">
<property name="testMapper">
<ref bean="testMapper" />
</property>
</bean>
这是配置文件mapper到 service的
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.xxx.*.dao" />
</bean>
这是配置文件,mapper注入到service的
@Service("testService")
public class TestServiceImpl implements TestService{
private TestMapper testMapper;
public TestMapper getTestMapper() {
return testMapper;
}
public void setTestMapper(TestMapper testMapper) {
this.testMapper = testMapper;
}
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
@Override
public Object tset1(){
TestMapper mapper = ApplicationContextFactory.getBean("testMapper", TestMapper.class);
mapper.insertOne();
throw new RuntimeException("test");
}
}
用配置文件方式的service
哎呦, 手敲的代码竟然都不见了
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zcloudMVC.mapper;com.emacle.docm.mapper" />
</bean>
我怎么感觉是配置文件上的问题呀?会不会是注入错了容器?
private TestMapper testMapper;
注入