spring+mybatis 配置mapper扫描无法注入
 applicationContext.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--获得属性文件里面的键值  -->                  
    <!-- <context:property-placeholder location="classpath*:*.properties" /> -->
    <!--扫描需要容器管理的类-->                   
    <context:component-scan base-package="com.nb"/> 
    <!-- 数据源 -->
    <bean name="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://127.0.0.1:3306/mynb?useUnicode=true&amp;characterEncoding=UTF-8</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>123456</value>
        </property>
    </bean>
    <!-- ================================ MyBatis SqlSession配置 ========================================= -->
    <!-- 使用SqlSessionFactoryBean工厂产生SqlSession对象,方便后期注入Dao -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--  <property name="configLocation" value="classpath:configuration.xml"></property>-->
        <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
        <property name="mapperLocations" value="classpath*:com/nb/dao/*.xml" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.nb.dao" />
        <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->        
    </bean>
    <!-- ================================= 事务控制相关 ============================================= -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" read-only="false" 
                       rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/>
            <tx:method name="insert*" propagation="REQUIRED" read-only="false" 
                       rollback-for="java.lang.RuntimeException" />
            <tx:method name="update*" propagation="REQUIRED" read-only="false" 
                       rollback-for="java.lang.Exception" />

            <tx:method name="find*" propagation="SUPPORTS"/>
            <tx:method name="get*" propagation="SUPPORTS"/>
            <tx:method name="select*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>    
    <aop:config>
        <aop:pointcut id="pc" expression="execution(* *.*.*(..))" />
        <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
    </aop:config>
</beans>



请问是什么原因呢,帮忙看看,谢谢

5个回答

测试类:
package com.nb.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.nb.domain.ent.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/spring/applicationContext.xml" })
public class UserManagerServiceTest {
@Autowired
IUserManagerService userManagerService;

@Test
public void testAddUser() {
    User user = new User();
    user.setUserName("jack");
    user.setPassword("123456");
    userManagerService.addUser(user);
}

}

 实现类:
 package com.nb.service;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nb.dao.UserMapper;
import com.nb.domain.ent.User;

@Service
@Transactional
public class UserManagerService implements IUserManagerService {

    @Autowired
    public UserMapper userMapper;

    @Override
    public int addUser(User user) {
        user.setId(UUID.randomUUID().toString());
        user.setUserName(user.getUserName());
        user.setPassword(user.getPassword());
        userMapper.insert(user);
        return userMapper.insert(user);
    }


}

dao:
package com.nb.dao;

import com.nb.domain.ent.User;

public interface UserMapper {
int insert(User record);

int insertSelective(User record);

}

错误:java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userManagerService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.nb.dao.UserMapper com.nb.service.UserManagerService.userMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.nb.dao.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory': : Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entMapper' defined in file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory': : Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entMapper' defined in file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory': : Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userMapper' defined in file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\UserMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory': : Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\Workspaces\gof\nb-parents\nb-service\target\classes\com\nb\dao\EntMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.nb.dao.EntMapper.BaseResultMap
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.nb.dao.UserMapper com.nb.service.UserManagerService.userMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.nb.dao.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 41 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.nb.dao.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 43 more

测试类没有加载ApplicationContext

annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
看到这句,就知道,你的bean对象没有产生。
做法:applicationContext.xml中添加UserMapper的bean

图片说明

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring+mybatis 配置mapper扫描无法注入

``` applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--获得属性文件里面的键值 --> <!-- <context:property-placeholder location="classpath*:*.properties" /> --> <!--扫描需要容器管理的类--> <context:component-scan base-package="com.nb"/> <!-- 数据源 --> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://127.0.0.1:3306/mynb?useUnicode=true&amp;characterEncoding=UTF-8</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>123456</value> </property> </bean> <!-- ================================ MyBatis SqlSession配置 ========================================= --> <!-- 使用SqlSessionFactoryBean工厂产生SqlSession对象,方便后期注入Dao --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- <property name="configLocation" value="classpath:configuration.xml"></property>--> <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 --> <property name="mapperLocations" value="classpath*:com/nb/dao/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.nb.dao" /> <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> --> </bean> <!-- ================================= 事务控制相关 ============================================= --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.RuntimeException" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="find*" propagation="SUPPORTS"/> <tx:method name="get*" propagation="SUPPORTS"/> <tx:method name="select*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pc" expression="execution(* *.*.*(..))" /> <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" /> </aop:config> </beans> 请问是什么原因呢,帮忙看看,谢谢

如何用属性注入的方式为spring的service注入Mybatis的Mapper对象?

万能的网友的。帮帮我吧。 spring+Mybatis+struts2整合中遇到一个问题:service层中不知道如何注入Mapper对象啊。 首先我分三层。action---> service---->Mapper(充当dao层)。 我的Mapper是扫描包生成实现类的。然而我的service里面有一个Mapper对象。 就像这样: public class ProductService { //@Autowired private ProductMapper productMapper; public void setProductMapper(ProductMapper productMapper) { this.productMapper = productMapper; } //省略其他代码。。。 } 然后我想通过setter方法将productMapper注入到ProductService中。 我的配置文件如下: <bean id="Mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name="basePackage" value="wm.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <bean id="productService" class="wm.service.ProductService" scope="prototype" > <property name="productMapper" ref=""></property> </bean> 写到这里,我忽然愣住了。这是我不知道ref该怎么写。或者还是value怎么写。如果用注解注入的话,我能解决这个问题。但是如果我用属性注入的方式怎么实现呢?大神们,没有分。不好意思啊。

mybatis 注入mapper的问题

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又可以取到并且操作,扫描包应是没问题的,不然应该会报错吧

ssm整合mapper注入失败

spring配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 加载资源文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 开启注解扫描 --> <context:component-scan base-package="com.spring"></context:component-scan> <!-- 配置数据源,并设置数据源 --> <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="driverClass" value="${jdbc.driver}"></property> <property name="maxPoolSize" value="500"></property> </bean> <!-- 配置sqlsessionfactory --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="c3p0DataSource"></property> <property name="configLocation" value="classpath:SqlMapConfig.xml"></property> </bean> <!-- 批量配置mybit的mapper接口,默认bean的id为类名首字母小写 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.spring.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property> </bean> <!-- jdbc事务管理器 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="c3p0DataSource"></property> </bean> <!-- 事务通知 --> <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager"> <tx:attributes> <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.spring.dao.*.*(..))" /> </aop:config> </beans> springmvc配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="com.spring"></context:component-scan> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsps/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> mybatis <configuration> <settings> <setting name="lazyLoadingEnabled" value="true" /> <setting name="aggressiveLazyLoading" value="false" /> <setting name="logImpl" value="LOG4J" /> </settings> <mappers> <mapper resource="com/spring/dao/Student.xml" /> </mappers> </configuration> 映射文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.spring.dao.StudentMapp"> <insert id="addStudent" parameterType="com.spring.dao.Student"> INSERT student (student_name) VALUES(#{student_name}) </insert> <delete id="delete"> delete from student where studentid=#{id} </delete> <select id="findstudentbyid" parameterType="int" resultType="com.spring.dao.Student"> select * from student where studentid=#{id} </select> <select id="findAllstudent" resultType="com.spring.dao.Student"> select * from student </select> <update id="update" parameterType="com.spring.dao.Student"> update student set student_name=#{student_name} where studentid=#{studentid} </update> </mapper>

[新手求助]spring整合mybatis时自动扫描错误

![个人javaweb结构](https://img-ask.csdn.net/upload/201610/23/1477193710_70439.jpg) 错误提示: Error creating bean with name 'org.mybatis.spring.mapper.MapperScannerConfigurer#0' defined in class path resource [config/applicationContext.xml] [application.xml配置文件如下] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 整合连接池druid:配置DataSource --> <bean name="datasource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- 整合MyBatis框架,配置sqlSessionFatory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="mapperLocations" value="classpath:config/UserMapper.xml" /> <property name="configLocation" value="classpath:config/mybatis-config.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <!-- 自动扫描注入 :此处有问题--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.spring.service"/> <property name="sqlSessionFactory" value="sqlSessionFactory" /> </bean> </beans> [web.xml配置如下] <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 整合监听器log4j --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:config/log4j.properties</param-value> </context-param> <!-- 整合SpringMVC --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 整合Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationContext.xml</param-value> </context-param> <!-- 字符集过滤器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 会话有效期(单位:分钟) --> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app> [serviceimpl如下] package org.spring.service.impl; import java.util.List; import org.mybatis.dao.UserDao; import org.mybatis.model.User; import org.spring.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service(value = "userService") public class UserServiceImpl implements UserService { @Autowired public UserDao userDao; @Override public boolean register(User model) { return userDao.register(model); } @Override public boolean login(User model) { return userDao.login(model); } @Override public List<User> findByXXX(User model) { return userDao.findByXXX(model); } } 求大神指点!!!

使用SpringMVC+Mybatis时,无法注入service

spring-mvc.xml中如下: <context:component-scan base-package="com.lyj" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> 我明明扫描了所有的包为什么还是找不到,出现如下异常: 九月 03, 2017 4:41:52 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Allocate exception for servlet spring org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.lyj.bookmanage.service.IUserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)} ![这是service](https://img-ask.csdn.net/upload/201709/03/1504428188_856272.png) ![这是controller](https://img-ask.csdn.net/upload/201709/03/1504428266_436346.png)

使用spring+Mybatis 注解无效

使用spring+Mybatis,使用spring注解,一直报空指针异常,各位麻烦看看 这个spring文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 使用注解式注入 --> <context:annotation-config /> <context:component-scan base-package="com/springMyBatis/system/service/*"/> <context:component-scan base-package="com/springMyBatis/system/dao/*"/> <!-- 配置数据源--> <import resource="application-db.xml" /> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource"> <ref bean="jdbcDataSource" /> </property> <!-- MyBatis 的 XML 配置文件路径 --> <property name="configLocation" value="classpath:com/springMyBatis/Mybatis.xml" /> <!-- 扫描自动生成的xml文件 --><!-- Mybatis XML映射文件 --> <property name="mapperLocations"> <list><!-- Mybatis XML映射文件 --> <value>classpath*:com/springMyBatis/system/mapper/*.xml</value> </list> </property> </bean> <!-- 扫描mybatisGenerator 自动生成的 所有接口--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com/springMyBatis/system/dao"></property> </bean> <!-- 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="jdbcDataSource" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="annotationClass" value="org.springframework.stereotype.Repository"/> <property name="basePackage" value="com.springMyBatis.system"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans> Mybatis配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="false" /> <!-- 查询时,关闭关联对象即时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="false" /> <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false" /> <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 允许使用列标签代替列名 --> <setting name="useColumnLabel" value="true" /> <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 --> <!-- <setting name="useGeneratedKeys" value="true" /> --> <!-- 给予被嵌套的resultMap以字段-属性的映射支持 --> <!-- <setting name="autoMappingBehavior" value="FULL" /> --> <!-- 对于批量更新操作缓存SQL以提高性能 --> <setting name="defaultExecutorType" value="BATCH" /> <!-- 数据库超过25000秒仍未响应则超时 --> <!-- <setting name="defaultStatementTimeout" value="25000" /> --> </settings> </configuration> DAO层接口 package com.springMyBatis.system.dao; import java.util.List; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.springMyBatis.system.model.User; @Repository @Transactional public interface UserDao { public List<User> selectAllUser(); } mapper.xml文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.springMyBatis.system.dao.UserDao"> <select id="selectAllUser" resultType="com.springMyBatis.system.model.User"> select * from user </select> </mapper> service层文件 package com.springMyBatis.system.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.springMyBatis.system.dao.UserDao; import com.springMyBatis.system.model.User; @Service public class Select { @Autowired private UserDao userdao; public List<User> selectAllUser(){ System.out.println(userdao); List<User> list=userdao.selectAllUser(); return list; } userdao一直为空,求大神指导下

@autowired注入mapper为null

service ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public int insertUser(User user) { int result=userMapper.insert(user); return result; } } ``` spring-dao ``` <context:component-scan base-package="com.zone.service"></context:component-scan> <context:property-placeholder location="classpath:resource/*.properties"/> <!-- 数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}" /> <property name="maxActive" value="10" /> <property name="minIdle" value="3" /> </bean> <!-- spring管理sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource"></property> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property> </bean> <!-- 配置扫描包,加载mapper代理对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zone.mapper"></property> </bean> ``` 包 ![图片说明](https://img-ask.csdn.net/upload/201812/11/1544516161_946392.png)

Spring整合Mybatis关于Dao注入失败的问题求解

抛出异常 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private pers.zww.grad.dao.IAdminDao pers.zww.grad.service.impl.AdminServiceImpl.adminDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pers.zww.grad.dao.IAdminDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=adminDao)} 此为自动生成的Mapper,我加了注解@Repository package pers.zww.grad.dao; import org.springframework.stereotype.Repository; import pers.zww.grad.vo.Admin; @Repository("adminDao") public interface IAdminDao { int deleteByPrimaryKey(String id); int insert(Admin record); int insertSelective(Admin record); Admin selectByPrimaryKey(String id); int updateByPrimaryKeySelective(Admin record); int updateByPrimaryKey(Admin record); Integer getCountByName(String name); Integer getCountByNameAndPass(String name,String password); } 这是Service里面注入 package pers.zww.grad.service.impl; 、、、 @Service("adminService") public class AdminServiceImpl implements IAdminService { @Autowired @Qualifier("adminDao") private IAdminDao adminDao; @Override public int deleteByPrimaryKey(String id) { // TODO Auto-generated method stub return 0; } 配置文件都已扫描过了,而且相关mybatis的如下: <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:pers/zww/grad/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="pers.zww.grad.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean>

IDEA做SSM框架整合时,出现无法加载mapper,导致无法注入。

今日学习SSM框架整合,整合以后,单独用测试类可以连接成功连接数据库,可是一加入MVC用TOMCAT启动,项目就会报错,错误内容为:Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 以下为项目各部分截图,有没有大佬帮我分析下,问题到底出在哪? ========================================================================================================================================== ![项目报错详细情况](https://img-ask.csdn.net/upload/201908/15/1565880941_652575.png) ## 项目报错详细情况 ![spring配置文件已经配置了mapper.xml路径和齐对应的接口扫描包](https://img-ask.csdn.net/upload/201908/15/1565880955_958792.png) ## spring配置文件已经配置了mapper.xml路径和齐对应的接口扫描包 ![编译文件夹target里已经编译出了mapper相关配置文件及接口类](https://img-ask.csdn.net/upload/201908/15/1565881099_526884.png) ## 编译文件夹target里已经编译出了mapper相关配置文件及接口类 ![mapper.xml里的namespace已经指明了接口路径](https://img-ask.csdn.net/upload/201908/15/1565881139_161198.png) ## mapper.xml里的namespace已经指明了接口路径 ![pom文件里也配置了resource源](https://img-ask.csdn.net/upload/201908/15/1565881159_416309.png) ## pom文件里也配置了resource源 ========================================================================================================================================== # 详细代码已经贴在下方,只选了几个配置文件及mapper接口类,service及controller应该没关系就没传! ============================================= # mybatis-config.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--添加缓存 引入第三方二级缓存 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="cacheEnabled" value="false"/> </settings> <!-- 配置数据源 default默认使用的数据源 --> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///orderuser"/> <property name="username" value="zhijia3278"/> <property name="password" value="0528"/> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="OrderUserMapper.xml"/> </mappers> </configuration> ``` # OrderUserMapper.java ``` package cn.tedu.mapper; import cn.tedu.domain.Order; import cn.tedu.domain.User; public interface OrderUserMapper { public User queryUser(String userId); public Order queryOrder(String orderId); public void updateUserPoints(User user); } ``` # OrderUserMapper.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.tedu.mapper.OrderUserMapper"> <select id="queryUser" parameterType="String" resultType="User"> select * from t_user where user_id=#{userId} </select> <select id="queryOrder" parameterType="String" resultType="Order"> select * from t_order where order_id=#{orderId} </select> <update id="updateUserPoints" parameterType="User"> update t_user set points=#{points} where user_id=#{userId} </update> </mapper> ``` # spring.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置内容 --> <context:component-scan base-package="cn.tedu"> </context:component-scan> <context:annotation-config></context:annotation-config> <!-- 持久层数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <!-- 4个属性 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///orderuser"/> <property name="username" value="zhijia3278"/> <property name="password" value="0528"/> </bean> <!-- sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据源注入 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描mybatis的独立配置文件 关闭二级缓存,驼峰命名 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!-- 映射文件扫描 --> <property name="mapperLocations" value="classpath:mapper/OrderUserMapper.xml" /> <!-- 别名包 --> <property name="typeAliasesPackage" value="cn.tedu.domain"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描的接口包 cn.tedu.mapper --> <property name="basePackage" value="cn.tedu.mapper"/> </bean> <!-- 注解驱动开启,@RequestMapping @RequestParam等 --> <mvc:annotation-driven/> <!-- 防止静态文件js css html访问被dispacherServlet拦截 --> <!-- localhost静态文件根目录 /static /js /css --> <!-- mapping 满足什么样子的访问地址 http://localhost:8080/js//1.js --> <mvc:resources location="/" mapping="/**"></mvc:resources> </beans> ``` # springmvc-servlet ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置内容 --> <context:component-scan base-package="cn.tedu"/> <!-- 注解驱动开启,@RequestMapping @RequestParam等 --> <mvc:annotation-driven/> <!-- 防止静态文件js css html访问被dispacherServlet拦截 --> <!-- localhost静态文件根目录 /static /js /css --> <!-- mapping 满足什么样子的访问地址 http://localhost:8080/js//1.js --> <mvc:resources location="/" mapping="/**"></mvc:resources> </beans> ``` # web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- tomcat启动加载spring.xml --> <!-- <init-param>--> <!-- <param-name>contextConfigLocation</param-name>--> <!-- <param-value>classpath:springmvc/springmvc-servlet.xml</param-value>--> <!-- </init-param>--> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` # pom.xml ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.tedu</groupId> <artifactId>SSMDemo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>SSM-DEMO01 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- <dependency>--> <!-- <groupId>junit</groupId>--> <!-- <artifactId>junit</artifactId>--> <!-- <version>4.12</version>--> <!-- <scope>compile</scope>--> <!-- </dependency>--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.13.RELEASE</version> </dependency> <!-- datasource --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.14</version> </dependency> <!-- spring mysql --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.13.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.8</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- spring mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- springmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.13.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.13.RELEASE</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>SSM-DEMO01</finalName> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <!-- 插件属性配置 --> <configuration> <!-- 端口 --> <port>8080</port> <!-- 项目访问路径 --> <path>/</path> <!-- 编解码 --> <uriEncoding>utf-8</uriEncoding> <useBodyEncodingForURI>true</useBodyEncodingForURI> </configuration> </plugin> </plugins> <resources> <resource> <directory>resource</directory> <includes> <include>**/*.xml</include> <include>mapper/*.xml</include> <include>mybatis/*.xml</include> <include>spring/*.xml</include> </includes> <!-- <filtering>true</filtering>--> </resource> </resources> </build> </project> ```

spring3+mybatis 注入空指针问题,请各位帮忙一下。

大家好,我刚学习三大框架,碰到一个空指针问题怎么都解决不了,快3天了,请帮忙下,谢谢了。 我测试所有的注入都是空指针 applicationContext.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc=" http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd" default-autowire="byName" default-lazy-init="false"> <!-- 开启自动扫描并注册Bean定义支持 --> <!-- <context:component-scan base-package="cn.xhf"></context:component-scan> --> <!-- 采用注释的方式配置bean --> <!-- <context:annotation-config /> --> <!-- 配置datasource源 --> <context:property-placeholder location="classpath:mysql.properties" /> <!-- 使用mysql配置属性值 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <property name="maxActive" value="${maxActive}"></property> <property name="maxIdle" value="${maxIdle}"></property> <property name="maxWait" value="${maxWait}"></property> <property name="defaultAutoCommit" value="${defaultAutoCommit}"></property> </bean> <!-- 配置sqlSessionFactory,同时制定数据源 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:Configuration.xml" /> </bean> <!-- 配置SqlSessionTemplate --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <constructor-arg index="1" value="BATCH" /> </bean> <!-- 配置dao --> <bean id="booksDao" class="cn.xhf.dao.impl.BooksDaoImpl"> <property name="sqlSession" ref="sqlSession"></property> </bean> <bean id="usersDao" class="cn.xhf.dao.impl.UsersDaoImpl"> <property name="sqlSession" ref="sqlSession"></property> </bean> <!-- 配置service --> <bean id="booksService" class="cn.xhf.service.impl.BooksServiceImpl" scope="prototype"> <property name="booksDao" ref="booksDao"></property> </bean> <bean id="usersService" class="cn.xhf.service.impl.UsersServiceImpl" scope="prototype"> <property name="usersDao" ref="usersDao"></property> </bean> <!-- 配置action --> <bean id="booksAction" class="cn.xhf.action.BooksAction" scope="prototype"> <property name="booksService" ref="booksService"></property> </bean> <bean id="usersAction" class="cn.xhf.action.UsersAction" scope="prototype"> <property name="usersService" ref="usersService"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="select*" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面配置 --> <!-- <aop:config> <aop:pointcut expression="execution(* cn.xhf.service.*.*(..))" id="method" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="method" /> </aop:config> --> </beans> ``` dao层 ``` package cn.xhf.dao.impl; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import cn.xhf.dao.BooksDao; import cn.xhf.pojo.Books; /** * */ public class BooksDaoImpl implements BooksDao { private SqlSession sqlSession; //就是这个空指针 ,其他bean也是空 @Override public int deleteBooksById(String bid) { return sqlSession.delete("books.deleteBooksById", bid); } @Override public int updataBooksById(String bid) { return sqlSession.update("books.updataBooksById", bid); } @Override public List<Books> findAll() { List<Books> booksList = new ArrayList<Books>(); booksList = sqlSession.selectList("books.findBooks"); return booksList; } @Override public List<Books> findBooksByKeyword(String bookName, String bookAuthor) { List<Books> bookList = new ArrayList<Books>(); // Books books = new Books(); // books.setBookName(bookName); // books.setBookAuthor(bookAuthor); // bookList = sqlSession.selectList("books.findBooks", books); return bookList; } @Override public int insertBooks(Books books) { return sqlSession.insert("books.insertBooks", books); } public SqlSession getSqlSession() { return sqlSession; } public void setSqlSession(SqlSession sqlSession) { this.sqlSession = sqlSession; } } ``` test方法 ``` package cn.xhf.pojo; import java.util.List; import cn.xhf.dao.BooksDao; import cn.xhf.dao.impl.BooksDaoImpl; public class TestBooks { public static void main(String[] args) { BooksDao booksDao = new BooksDaoImpl(); List<Books> list = booksDao.findAll(); System.out.println(list.size()); } } ``` 报错信息: Exception in thread "main" java.lang.NullPointerException at cn.xhf.dao.impl.BooksDaoImpl.findAll(BooksDaoImpl.java:32) at cn.xhf.pojo.TestBooks.main(TestBooks.java:11)

spring和mybatis合并application.xml配置bean问题

![图片说明](https://img-ask.csdn.net/upload/201605/30/1464539010_890467.png)spring和mybatis合并后在application.xml中配置bean,使用的是mapper扫描器,报错如下,请大神解决 org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [F:\workspace\SpringmMybatis529\bin\cn\itcast\mybatis\mapper\UsersMapper.class]; nested exception is java.lang.IllegalArgumentException at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:281) at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242) at org.mybatis.spring.mapper.ClassPathMapperScanner.doScan(ClassPathMapperScanner.java:155) at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.scan(ClassPathBeanDefinitionScanner.java:220) at org.mybatis.spring.mapper.MapperScannerConfigurer.postProcessBeanDefinitionRegistry(MapperScannerConfigurer.java:315) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at cn.itcast.mybatis.mapper.UsersMapperTest.setUp(UsersMapperTest.java:15) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:292) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:257) ... 32 more

spring整合mybatis 注入出错 求助各位大神

![目录结构](https://img-ask.csdn.net/upload/201704/13/1492074562_72832.png) 报错 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cn.jscoin.UserTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.jscoin.jslj.mapper.UserMapper cn.jscoin.UserTest.userMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cn.jscoin.jslj.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:252) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:254) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.jscoin.jslj.mapper.UserMapper cn.jscoin.UserTest.userMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cn.jscoin.jslj.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:558) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cn.jscoin.jslj.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:530) ... 28 more 测试代码 ``` @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath*:applicationContext.xml") public class UserTest { @Autowired private UserMapper userMapper; @Test public void testAdd(){ User user = new User(); user.setAge(123); userMapper.add(user); } } ``` ![配置文件位置](https://img-ask.csdn.net/upload/201704/13/1492074774_341390.png) applicationContext.xml <!-- 扫描包 --> <context:component-scan base-package="cn.jscoin" /> <!-- 数据源 druid --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <!-- 读取Property --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <set> <value>classpath:jdbc.properties</value> </set> </property> </bean> <!-- Mybatis工厂 --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 配置Mybati的核心配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- 扫描基本包 Mapper 接口 Mapper文件 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.jscoin.jslj.mapper" /> </bean> <!-- 事务 @Transactional --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启注解的事务 --> <tx:annotation-driven transaction-manager="transactionManager" />

ssm项目springmvc中加入websocke后mybatis不能注入mapper

spring——mybatis文件 ``` <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="autoCommitOnClose" value="true"/> <!-- property name="checkoutTimeout" value="${cpool.checkoutTimeout}"/ --> <property name="initialPoolSize" value="${cpool.initialPoolSize}"/> <property name="minPoolSize" value="${cpool.minPoolSize}"/> <property name="maxPoolSize" value="${cpool.maxPoolSize}"/> <property name="maxIdleTime" value="${cpool.maxIdleTime}"/> <property name="acquireIncrement" value="${cpool.acquireIncrement}"/> <property name="idleConnectionTestPeriod" value="${cpool.idleConnectionTestPeriod}"/> <property name="acquireRetryAttempts" value="${cpool.acquireRetryAttempts}"/> <property name="maxStatements" value="${c3p0.maxStatements}"/> <property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- mapper和resultmap配置路径 --> <property name="mapperLocations"> <list> <value>classpath:com/yuan/*/entity/*.mapper.xml</value> </list> </property> </bean> <!-- 设置扫描根路径也就是你的mybatis的mapper接口所在包路径; 凡是markerInterface这个接口的子接口都参与到这个扫描, 也就是说所有的mapper接口继承这个SqlMapper。--> <bean name="SqlMapper" class="com.yuan.framework.mapper.SqlMapper"> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.yuan.*.mapper"/> <property name="markerInterface" ref="SqlMapper" /> </bean> <!-- TransactionManager 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--启动spring事务注解功能--> <tx:annotation-driven transaction-manager="transactionManager" /> ``` springmvc文件 ``` <mvc:annotation-driven/> <!-- <mvc:resources location="/" mapping="/**"/> --> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 --> <context:component-scan base-package="com.yuan.*.controller" /> <bean id="myHandler" class="com.yuan.framework.websocket.WebsocketEndPoint"></bean> <websocket:handlers> <websocket:mapping path="/myHandler" handler="myHandler"/> <websocket:handshake-interceptors> <bean class="com.yuan.framework.websocket.HandshakeInterceptor"/> </websocket:handshake-interceptors> </websocket:handlers> <!-- <websocket:handlers > <websocket:mapping path="/sockjs/myHandler" handler="myHandler"/> <websocket:sockjs/> </websocket:handlers> --> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --> </list> </property> <!-- 日期格式转换 --> <property name="webBindingInitializer"> <bean class="com.yuan.framework.util.DateConverter"/> </property> </bean> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 --> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> ```

spring-boot和mybatis配置多数据源,service找不到bean

# 在配置多数据源时候在service层的时候如果只用@Autowired的时候会因为有多个数据源而报错,但当我加上@Qualifier("sqlSessionFactory")的时候又会查不到对应的bean是我的注解写的有问题? 配置文件如下 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 读取数据库连接信息配置 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:db.properties" /> </bean> <!-- 配置数据源连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="100"/> <property name="initialSize" value="5"/> <property name="minIdle" value="5"/> <property name="maxWait" value="60"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT 1"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="true"/> <property name="testOnReturn" value="false"/> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> </bean> <!-- 配置数据源管理对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> --> <property name="mapperLocations" value="classpath:com/ocss/sqlmap/*.xml" /> <property name="typeAliasesPackage" value="com.ocss.dao"/> </bean> <!-- 配置数据源自动实装 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ocss.dao" /> <property name="processPropertyPlaceHolders" value="true" /> <!-- <property name="sqlSessionTemplateBeanName" value="sqlSessionFactory" /> --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!-- 配置数据源事务控制 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 配置数据源连接池2 --> <bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName2}"/> <property name="url" value="${jdbc.url2}"/> <property name="username" value="${jdbc.username2}"/> <property name="password" value="${jdbc.password2}"/> <property name="maxActive" value="100"/> <property name="initialSize" value="5"/> <property name="minIdle" value="5"/> <property name="maxWait" value="60"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT 1"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="true"/> <property name="testOnReturn" value="false"/> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> </bean> <!-- 配置数据源管理对象 --> <bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource2" /> <!-- <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> --> <property name="mapperLocations" value="classpath:com/his/sqlmap/*.xml" /> <property name="typeAliasesPackage" value="com.his.dao"/> </bean> <!-- 配置数据源自动实装 --> <bean id="mapperScanner2" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.his.dao" /> <property name="processPropertyPlaceHolders" value="true" /> <property name="sqlSessionTemplateBeanName" value="sqlSessionFactory2" /> <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2" /> --> </bean> <bean id="sqlSession2" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory2" /> </bean> <!-- 配置数据源事务控制 --> <bean id="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource2" /> </bean> <tx:annotation-driven transaction-manager="transactionManager2" /> </beans> ## service如下 @Service public class InfoContentServiceImpl implements InfoContentService { @Autowired //@Qualifier("sqlSessionFactory") private InfoContentDao infoContentDao;

Sping Boot注入接口失败

![图片说明](https://img-ask.csdn.net/upload/201804/21/1524291637_361310.png) 项目结构应该是正确的。 ``` @Repository public interface UserDao { public User getById(int id); } ``` Dao层的代码,使用接口。 @Service ``` @Service public class UserService { @Autowired UserDao userDao; public User getById(int id) { return userDao.getById(id); } } ``` service层代码。 controller层注入service。 启动spring boot后会提示dao层没有扫描到,如果@ComponentScan dao层的话,会提示service层注入失败,求解。

Spring和Mybatis整合后注入报错

新手入门,最近在学习框架整合的时候遇到一个问题,就是配置好必须的文件后,测试的时候发现用@Resource注入直接报错。找了很久都不知道什么原因,求大神们帮助T T 直接贴图。 spring-mybatis.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.schoolmarket.ssm"/> <!-- 第一种方式:加载一个properties文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- 第二种方式:加载多个properties文件 <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:common.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8"/> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties"/> </bean> --> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClasss}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <property name="basePackage" value="com.schoolmarket.ssm.dao"/> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` User.java ``` package com.schoolmarket.ssm.model; public class User { private String uid; private String username; private String pwd; private String phone; private String address; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } ``` UserDao.java ``` package com.schoolmarket.ssm.dao; import com.schoolmarket.ssm.model.User; public interface UserDao { User selectById(String uid); } ``` UserMapping.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.schoolmarket.ssm.dao.UserDao"> <select id="selectById" resultType="com.schoolmarket.model.User" parameterType="String"> select uid,username,pwd,phone,address from users where uid = #{uid} </select> </mapper> ``` IUserService.java ``` package com.schoolmarket.ssm.service; import com.schoolmarket.ssm.model.User; public interface IUserService { public User getUserById(String uid); } ``` UserServiceImpl.java ``` package com.schoolmarket.ssm.service; import com.schoolmarket.ssm.dao.UserDao; import com.schoolmarket.ssm.model.User; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service("userService") public class UserServiceImpl implements IUserService { @Resource private UserDao userDao; public User getUserById(String uid) { return userDao.selectById(uid); } } ``` 那么重点来了。 ![图片说明](https://img-ask.csdn.net/upload/201610/28/1477619092_506993.png)

为什么 我这个地方的mapper 文件读取不到呢spring整合mybatis

# 问题解决了 没有去除掉classpath* 顺便百度了下这两者区别 classpath和classpath*区别: classpath:只会到你的class路径中查找找文件。 classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。 注意: 用classpath*:需要遍历所有的classpath,所以加载速度是很慢的;因此,在规划的时候,应该尽可能规划好资源文件所在的路径,尽量避免使用classpath* ```<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.itheima"> <!-- 不扫描有controller 注解的bean--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--加载JDBC 文件 --> <context:property-placeholder location="classpath*:jdbc.properties"/> <!-- 注入--> <!-- C3P0 --> <!--<bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">--> <!--<property name="driverClass" value="${jdbc.driver}"/>--> <!--<property name="jdbcUrl" value="${jdbc.url}"/>--> <!--<property name="user" value="${jdbc.username}"/>--> <!--<property name="password" value="${jdbc.password}"/>--> <!--</bean>--> <!-- Druid--> <bean class="com.alibaba.druid.pool.DruidDataSource" id="druidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--JDBC模板注入 --> <!--<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">--> <!--<property name="dataSource" ref="c3p0" />--> <!--</bean>--> <!-- 配置核心配置文件sqlsessionconfig --> <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> <property name="dataSource" ref="druidDataSource"/> <property name="configLocation" value="classpath*:sqlMapConfig.xml"/> <property name="mapperLocations" value="classpath*:common/itheima/mapper/*.xml"/> <property name="typeAliasesPackage" value="com.itheima.domian"/> </bean> <!-- 自动扫描 将Mapper接口生成代理注入到Spring --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <property name="basePackage" value="com.itheima.mapper"/> </bean> <!-- 数据源事务管理器 --> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="druidDataSource"/> </bean> <!-- -配置事务增强 --> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置切面类 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:advisor> </aop:config> </beans> ```这个是applicationContext.xml ```现在的问题是访问不到这个mapper下方是mybatis核心配置的文件 ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!----> <typeAliases> <typeAlias type="com.itheima.domain.User" alias="User" /> <typeAlias type="com.itheima.domian.Role" alias="Role" /> </typeAliases> <mappers> <package name="common.itheima.mapper" /> <!--<mapper resource="com/itheima/mapper/UserMapper.xml" />--> </mappers> </configuration> ``` mapper文件如下 ``` <select id="findAllUser" resultType="User"> SELECT *FROM sys_user </select> ```java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userMapper' defined in file [D:\IdeaProject\JavaEE_Code\homework\ssm-test02\target\classes\com\itheima\mapper\UserMapper.class]: Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [classpath*:sqlMapConfig.xml] cannot be opened because it does not exist at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) at org.springframework.beans.factory.annotation.AutowiredAnnot ``` ``` ``` ``` mapper如下 ``` public interface UserMapper { /* * 查看用户 * */ // @Select("select *from sys_user ") List<User> findAllUser(); } ```已解决 ----------------------------------------------------------------- classpath出问题了 解决成功!

springboot使用了通用mapper后再自定义mapper产生的bug,求助

1、如果启动类上的@mapperScan(basePackages = "com.imooc.mapper")和application.yml的mybatis配置mapper-locations = "classpath:mapper/*.xml "同时存在的话。则启动时会出现某些bean无法被创建![图片说明](https://img-ask.csdn.net/upload/202005/21/1590027406_520395.png) 2.如果注释掉mapper-locations,则可以正常启动,但是只能扫描到通用mapper无法扫描到自定义mapper![图片说明](https://img-ask.csdn.net/upload/202005/21/1590027484_968513.png) 通用mapper与自定义mapper放在同一个包下,已确定自定义mapper.xml没有任何错误。为什么会出现这种情况?如果让mapper-locations指定扫描一个自定义mapper.xml,则两种bug都不会出现。可是要是有多个自定义mapper该怎么解决?

SpringMVC mybatis注入Dao层失败

BaseDaoImpl.java ``` public class BaseDaoImpl<T> extends SqlSessionDaoSupport { @Resource public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } public List<QuestionOption> GetTest() { return getSqlSession().selectList("executeSql", "SELECT * FROM xxx"); } } ``` BaseDao.java ``` public interface BaseDao { public List<QuestionOption> GetTest(); } ``` QuestionBankServiceImpl.java ``` @Transactional @Service("QuestionBankService") public class QuestionBankServiceImpl implements IQuestionBankService { @Resource private IQuestionBankDao questionBankDao; public List<QuestionOption> GetTest() { List<QuestionOption> list=questionBankDao.GetTest(); return list; } } ``` spring-mvc.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <mvc:annotation-driven /> <mvc:resources location="/images/" mapping="/images/**" /> <mvc:resources location="/css/" mapping="/css/**" /> <mvc:resources location="/js/" mapping="/js/**" /> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.TJ.test.controller" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- 全局异常处理 自定义实现spring的全局异常解析器HandlerExceptionResolver --> <bean id="exceptionResolver" class="com.anyi.globallicai.mvcframework.CustomExceptionResolver"></bean> </beans> ``` spring-mybatis.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.Tj.test.*" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:conf/jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:conf/mybatis-config.xml"></property> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/Tj/test/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.TJ.test.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> ``` BaseDao 我想写一些基础的 增删改查 然后 以后dao的每个class 直接继承 BaseDao 在Service直接调用就可以了 现在 运行调用之后 提示 Invalid bound statement (not found): com.Tj.test.dao.IQuestionBankDao.GetTest 所以怀疑没有注入成功 ![结构目录](https://img-ask.csdn.net/upload/201808/20/1534754528_778233.jpg)

C/C++学习指南全套教程

C/C++学习的全套教程,从基本语法,基本原理,到界面开发、网络开发、Linux开发、安全算法,应用尽用。由毕业于清华大学的业内人士执课,为C/C++编程爱好者的教程。

定量遥感中文版 梁顺林著 范闻捷译

这是梁顺林的定量遥感的中文版,由范闻捷等翻译的,是电子版PDF,解决了大家看英文费时费事的问题,希望大家下载看看,一定会有帮助的

YOLOv3目标检测实战:训练自己的数据集

YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!

sql语句 异常 Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your

在我们开发的工程中,有时候会报 [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ------ 这种异常 不用多想,肯定是我们的sql语句出现问题,下面...

浪潮集团 往年的软件类 笔试题 比较详细的哦

浪潮集团 往年的软件类 笔试题 比较详细的哦

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

I2c串口通信实现加速度传感器和FPGA的交流

此代码能实现加速度传感器与FPGA之间的交流,从而测出运动物体的加速度。

Python可以这样学(第一季:Python内功修炼)

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

微信公众平台开发入门

本套课程的设计完全是为初学者量身打造,课程内容由浅入深,课程讲解通俗易懂,代码实现简洁清晰。通过本课程的学习,学员能够入门微信公众平台开发,能够胜任企业级的订阅号、服务号、企业号的应用开发工作。 通过本课程的学习,学员能够对微信公众平台有一个清晰的、系统性的认识。例如,公众号是什么,它有什么特点,它能做什么,怎么开发公众号。 其次,通过本课程的学习,学员能够掌握微信公众平台开发的方法、技术和应用实现。例如,开发者文档怎么看,开发环境怎么搭建,基本的消息交互如何实现,常用的方法技巧有哪些,真实应用怎么开发。

机器学习初学者必会的案例精讲

通过六个实际的编码项目,带领同学入门人工智能。这些项目涉及机器学习(回归,分类,聚类),深度学习(神经网络),底层数学算法,Weka数据挖掘,利用Git开源项目实战等。

eclipseme 1.7.9

eclipse 出了新的eclipseme插件,官方有下载,但特慢,我都下了大半天(可能自己网速差)。有急需要的朋友可以下哦。。。

Spring Boot -01- 快速入门篇(图文教程)

Spring Boot -01- 快速入门篇 今天开始不断整理 Spring Boot 2.0 版本学习笔记,大家可以在博客看到我的笔记,然后大家想看视频课程也可以到【慕课网】手机 app,去找【Spring Boot 2.0 深度实践】的课程,令人开心的是,课程完全免费! 什么是 Spring Boot? Spring Boot 是由 Pivotal 团队提供的全新框架。Spring Boot...

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

最简单的倍频verilog程序(Quartus II)

一个工程文件 几段简单的代码 一个输入一个输出(50Mhz倍频到100Mhz)

计算机组成原理实验教程

西北工业大学计算机组成原理实验课唐都仪器实验帮助,同实验指导书。分为运算器,存储器,控制器,模型计算机,输入输出系统5个章节

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

基于RSA通信密钥分发的加密通信

基于RSA通信密钥分发的加密通信,采用pycrypto中的RSA、AES模块实现

不同变质程度煤尘爆炸残留气体特征研究

为分析不同变质程度煤尘爆炸残留气体成分的特征规律,利用水平管道煤尘爆炸实验装置进行了贫瘦煤、肥煤、气煤、长焰煤4种不同变质程度的煤尘爆炸实验,研究了不同变质程度煤尘爆炸后气体残留物含量的差异,并对气体

设计模式(JAVA语言实现)--20种设计模式附带源码

课程亮点: 课程培训详细的笔记以及实例代码,让学员开始掌握设计模式知识点 课程内容: 工厂模式、桥接模式、组合模式、装饰器模式、外观模式、享元模式、原型模型、代理模式、单例模式、适配器模式 策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式 课程特色: 笔记设计模式,用笔记串连所有知识点,让学员从一点一滴积累,学习过程无压力 笔记标题采用关键字标识法,帮助学员更加容易记住知识点 笔记以超链接形式让知识点关联起来,形式知识体系 采用先概念后实例再应用方式,知识点深入浅出 提供授课内容笔记作为课后复习以及工作备查工具 部分图表(电脑PC端查看):

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

几率大的Redis面试题(含答案)

本文的面试题如下: Redis 持久化机制 缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题 热点数据和冷数据是什么 Memcache与Redis的区别都有哪些? 单线程的redis为什么这么快 redis的数据类型,以及每种数据类型的使用场景,Redis 内部结构 redis的过期策略以及内存淘汰机制【~】 Redis 为什么是单线程的,优点 如何解决redis的并发竞争key问题 Red...

手把手实现Java图书管理系统(附源码)

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化

jsp+servlet入门项目实例

jsp+servlet实现班级信息管理项目

winfrom中嵌套html,跟html的交互

winfrom中嵌套html,跟html的交互,源码就在里面一看就懂,很简单

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

python实现数字水印添加与提取及鲁棒性测试(GUI,基于DCT,含测试图片)

由python写的GUI,可以实现数字水印的添加与提取,提取是根据添加系数的相关性,实现了盲提取。含有两种攻击测试方法(高斯低通滤波、高斯白噪声)。基于python2.7,watermark.py为主

Xshell6完美破解版,亲测可用

Xshell6破解版,亲测可用,分享给大家。直接解压即可使用

你连存活到JDK8中著名的Bug都不知道,我怎么敢给你加薪

CopyOnWriteArrayList.java和ArrayList.java,这2个类的构造函数,注释中有一句话 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public ArrayList(Collection&lt;? ...

相关热词 c#中如何设置提交按钮 c#帮助怎么用 c# 读取合并单元格的值 c#带阻程序 c# 替换span内容 c# rpc c#控制台点阵字输出 c#do while循环 c#调用dll多线程 c#找出两个集合不同的
立即提问