AOP切mybatis的mapper接口,切不到接口上的annotation 100C

如题,一个springboot项目,mapper接口上有自定义的类型级注解PrivateDatasource,
表达式如下:
@Around("execution(* com.nbst.dao.mapper.idevcloudweb.*.*(..)) && @target(privateDatasource)")
切接口是切不到注解,但是自己给一个普通类上加上注解就可以切到,请问有大佬能给解答一下么

切面类:
@Aspect
@Component
public class DataSourceAspect {
@Around("execution(* com.nbst.dao.mapper.idevcloudweb.*.*(..)) && ( @target(privateDatasource) || @annotation(privateDatasource) )")
public Object beforeMapper(ProceedingJoinPoint joinPoint,PrivateDatasource privateDatasource){
Signature sig = joinPoint.getSignature();
String method = sig.getName();
System.out.println("方法名:"+sig.getName());
if(privateDatasource == null){
Object target = joinPoint.getTarget();
privateDatasource = target.getClass().getAnnotation(PrivateDatasource.class);
}
System.out.println(privateDatasource.value());
return null;
}
}
mapper接口:
@PrivateDatasource
public interface CompanyMapper
同一路径下的用于测试的类:
@PrivateDatasource
@Component
public class Test {
public void say(){
System.out.println("test");
}
}
根本切不到带注解的接口,也就是无法注入注解对象作为参数,但是普通类是可以切到、并且将注解对象作为参数注入的

youxiu326
奇衡三✎ springboot 2x版本可以拦截到
12 个月之前 回复
qq_34382367
Jason.Tang annotation是切不到的,但是可以通过execution的方式可以切到,在依赖注入DAO的地方加上@Lazy即可,如果切的地方不同的类型的时候可以加自定义注解作为区分
一年多之前 回复

9个回答

切面类:
@Aspect
@Component
public class DataSourceAspect {
@Around("execution(* com.nbst.dao.mapper.idevcloudweb.*.*(..)) && ( @target(privateDatasource) || @annotation(privateDatasource) )")
public Object beforeMapper(ProceedingJoinPoint joinPoint,PrivateDatasource privateDatasource){
Signature sig = joinPoint.getSignature();
String method = sig.getName();
System.out.println("方法名:"+sig.getName());
if(privateDatasource == null){
Object target = joinPoint.getTarget();
privateDatasource = target.getClass().getAnnotation(PrivateDatasource.class);
}
System.out.println(privateDatasource.value());
return null;
}
}
mapper接口:
@PrivateDatasource
public interface CompanyMapper
同一路径下的用于测试的类:
@PrivateDatasource
@Component
public class Test {
public void say(){
System.out.println("test");
}
}
根本切不到带注解的接口,也就是无法注入注解对象作为参数,但是普通类是可以切到、并且将注解对象作为参数注入的

可以发代码研究下。。。。。。

zm12397
zm12397 您好,代码发在上面了
2 年多之前 回复

springAOP基于动态代理,有两种方式,一种是默认的基于jdk动态代理,这种是不能对接口进行代理的
还有一种是基于cglib的代理 这种接口也可以代理,我估计你是没有开启cglib代理,就是默认的jdk代理,
加上这个配置就是强制使用cglib代理

zm12397
zm12397 这个没有影响的,把@target去掉只用包的路径来切的话是可以切到接口的,打印出来目标对象其实是代理对象,但是代理对象反射发现没有注解,所以问题应该还是注解上。。
2 年多之前 回复

图片说明
这段配置加上去试试,默认使用cglib代理的,代码好像贴上去好像不显示

wb_snail
wb_snail 回复zm12397: 哦好吧,这样应该是不行的,mybatis会动态创建mapper接口的实现类去执行sql,而你用aop加在接口上,代理实现方式也是动态创建接口的实现类然后切入点的前后加上你要加的逻辑,除非mybatis和spring aop为这个接口创建的是一个实现类,不然就不能实现你的功能,你可以把切入点写在调用dao的service方法上
2 年多之前 回复
zm12397
zm12397 回复wb_snail: mybatis的mapper接口,没用实现类
2 年多之前 回复
wb_snail
wb_snail 回复zm12397: 接口的实现类和实现方法呢,贴来看看
2 年多之前 回复
zm12397
zm12397 这个没有影响的,把@target去掉只用包的路径来切的话是可以切到接口的,打印出来目标对象其实是代理对象,但是代理对象反射发现没有注解,所以问题应该还是注解上。。
2 年多之前 回复

反射打印下发现普通类切到了,而且注解作为参数是可以拿到的
方法名:say
注解:@com.nbst.annotation.PrivateDatasource(value=PUBLIC)
但是接口的还是不行,注解根本注入不进去
方法名:findByCondition
注解:null

springAOP基于动态代理,有两种方式,一种是默认的基于jdk动态代理,这种是不能对接口进行代理的
还有一种是基于cglib的代理 这种接口也可以代理,我估计你是没有开启cglib代理,就是默认的jdk代理,
加上这个配置就是强制使用cglib代理

你得吧这个类给ioc容器,就是交给spring管理,也就是@Component,spring才能管理,才会知道给你的切点进行增强处理。

切不了,源码中明确写了,判断的是target method上的注解,你注解定义在接口上,这个接口的实现类上没用注解,那么就判断这个实现类方法不被拦截,因为一个实现类能够实现多个接口,为了避免多接口方法同注解的情况,aspectjweaver.jar中并没有实现接口方法上注解的处理,你可以自己改写pectjweaver.jar中org.aspectj.weaver.reflect.ReflectionBasedResolvedMemberImpl.unpackAnnotations()方法

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
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)

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>

为什么 我这个地方的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出问题了 解决成功!

mybatis中mapper配置问题

第一次创建,报一下这些错误,求解决!求解决!不知道usermapper哪里出问题 D:\Java\jdk1.8.0_172\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2018.1.5\lib\idea_rt.jar=58476:C:\Program Files\JetBrains\IntelliJ IDEA 2018.1.5\bin" -Dfile.encoding=UTF-8 -classpath D:\Java\jdk1.8.0_172\jre\lib\charsets.jar;D:\Java\jdk1.8.0_172\jre\lib\deploy.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_172\jre\lib\javaws.jar;D:\Java\jdk1.8.0_172\jre\lib\jce.jar;D:\Java\jdk1.8.0_172\jre\lib\jfr.jar;D:\Java\jdk1.8.0_172\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_172\jre\lib\jsse.jar;D:\Java\jdk1.8.0_172\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_172\jre\lib\plugin.jar;D:\Java\jdk1.8.0_172\jre\lib\resources.jar;D:\Java\jdk1.8.0_172\jre\lib\rt.jar;D:\workplace\webssm\target\classes;D:\mavenRepository\jstl\jstl\1.2\jstl-1.2.jar;D:\mavenRepository\javax\javaee-api\7.0\javaee-api-7.0.jar;D:\mavenRepository\com\sun\mail\javax.mail\1.5.0\javax.mail-1.5.0.jar;D:\mavenRepository\javax\activation\activation\1.1\activation-1.1.jar;D:\mavenRepository\org\mybatis\mybatis\3.3.0\mybatis-3.3.0.jar;D:\mavenRepository\mysql\mysql-connector-java\5.1.29\mysql-connector-java-5.1.29.jar;D:\mavenRepository\commons-dbcp\commons-dbcp\1.2.2\commons-dbcp-1.2.2.jar;D:\mavenRepository\commons-pool\commons-pool\1.3\commons-pool-1.3.jar;D:\mavenRepository\com\alibaba\fastjson\1.1.41\fastjson-1.1.41.jar;D:\mavenRepository\log4j\log4j\1.2.17\log4j-1.2.17.jar;D:\mavenRepository\org\slf4j\slf4j-api\1.7.18\slf4j-api-1.7.18.jar;D:\mavenRepository\org\slf4j\slf4j-log4j12\1.7.18\slf4j-log4j12-1.7.18.jar;D:\mavenRepository\org\codehaus\jackson\jackson-mapper-asl\1.9.13\jackson-mapper-asl-1.9.13.jar;D:\mavenRepository\org\codehaus\jackson\jackson-core-asl\1.9.13\jackson-core-asl-1.9.13.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-core\2.8.0\jackson-core-2.8.0.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-databind\2.8.0\jackson-databind-2.8.0.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;D:\mavenRepository\commons-fileupload\commons-fileupload\1.3.1\commons-fileupload-1.3.1.jar;D:\mavenRepository\commons-io\commons-io\2.4\commons-io-2.4.jar;D:\mavenRepository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar com.controller.test Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may exist in com/mapper/UserMapper.java (best guess) ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:54) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:38) at com.controller.test.main(test.java:25) Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:115) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:95) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:52) ... 2 more Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:259) at org.apache.ibatis.parsing.XPathParser.<init>(XPathParser.java:125) at org.apache.ibatis.builder.xml.XMLMapperBuilder.<init>(XMLMapperBuilder.java:78) at org.apache.ibatis.builder.xml.XMLMapperBuilder.<init>(XMLMapperBuilder.java:73) at org.apache.ibatis.builder.annotation.MapperAnnotationBuilder.loadXmlResource(MapperAnnotationBuilder.java:166) at org.apache.ibatis.builder.annotation.MapperAnnotationBuilder.parse(MapperAnnotationBuilder.java:118) at org.apache.ibatis.binding.MapperRegistry.addMapper(MapperRegistry.java:72) at org.apache.ibatis.session.Configuration.addMapper(Configuration.java:671) at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:348) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:113) ... 4 more Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 <mapper namespace="com.mapper.UserMapper"> <resultMap type="com.pojo.User" id="userResultMap"> <id property="id" colum="id"/> <result property="username" column="username"/> <result property="sex" column="sex"/> <result property="age" column="age"/> <result property="loginname" column="loginname"/> <result property="password" column="password"/> <result property="phone" column="phone"/> <result property="address" column="address"/> <!-- 一对多关联映射--> <collection property="orders" javaType="ArrayList" column="id" ofType="com.pojo.User" select="com.mapper.OrderMapper.selectOrderByUserId" fetchType="lazy"> <id property="id" colum="id"></id> <result property="code" column="code"></result> <result property="total" column="total"></result> </collection> </resultMap> <select id="selectUserById" parameterType="int" resultMap="userResultMap"> SELECT * FROM user WHERE id = #{id} </select> </mapper> package com.controller; import com.mapper.OrderMapper; import com.mapper.UserMapper; import com.pojo.Order; import com.pojo.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.*; //import org.mybatis.spring.SqlSessionFactoryBean; //import org.springframework.aop.scope.ScopedProxyUtils; import java.io.IOException; //import java.io.InputStream; import java.io.Reader; import java.util.List; public class test { public static void main(String[] args) throws IOException { //读取mybatis-config.xml文件 //InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml"); Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); //初始化mybatis,创建sqlsessionfactory类的实例 SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); //创建Session实例 SqlSession session=sqlSessionFactory.openSession(); test t=new test(); t.testSelectUserById(session); t.testSelectOrderById(session); session.commit(); session.close(); } //测试一对多关系 public void testSelectUserById(SqlSession session){ //获得usermapper接口的代理对象 UserMapper um=session.getMapper(UserMapper.class); //调用selectUserById方法 User user=um.selectUserById(1); //查询user的对象信息 System.out.println(user.getId()+""+user.getUsername()); List<Order> orders=user.getOrders(); for (Order order:orders ) { System.out.println(order); } } //测试多对多的关系,查询订单Order的时候级联查询订单的商品 public void testSelectOrderById(SqlSession session){ //获得OrderMapper接口的代理对象 OrderMapper om=session.getMapper(OrderMapper.class); //调用selectOrderById方法 Order order=om.selectOrderById(2); //查看查询到的信息 System.out.println(order.getId()+""+order.getCode()+""+order.getTotal()); User user=order.getUser(); System.out.println(user); } }

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;

Spring Boot + Mybatis 配置多数据源出错

刚接触Spring Boot 不久,今天用 Spring Boot + Mybatis 按照网上的方法配置多数据源, 配置了多个DataConfig,并给其中一个打上了Primary注解,现在出现这样的问题: 给哪个数据源加Primary注解哪个数据源才能查询成功,其他的数据源一查就报异常,搞了好久不知道哪出的问题,各位大婶帮忙看看,下面是堆栈信息 org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.ExampleProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.ExampleProvider at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:79) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447) at com.sun.proxy.$Proxy62.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:231) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:128) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:68) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53) at com.sun.proxy.$Proxy67.selectByExample(Unknown Source) at com.hworld.clp.component.companysetting.CompanySettingComponentImpl.getVerifyCodeSettings(CompanySettingComponentImpl.java:38) at com.hworld.clp.service.member.MemberServiceImpl.verifyCodeSetting(MemberServiceImpl.java:368) at com.hworld.clp.service.member.MemberServiceImpl.sendVerifyCode(MemberServiceImpl.java:280) at com.hworld.clp.controller.member.MemberController.sendVerifyCode(MemberController.java:78) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.ibatis.builder.BuilderException: Error invoking SqlProvider method (tk.mybatis.mapper.provider.ExampleProvider.dynamicSQL). Cause: java.lang.InstantiationException: tk.mybatis.mapper.provider.ExampleProvider at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:102) at org.apache.ibatis.builder.annotation.ProviderSqlSource.getBoundSql(ProviderSqlSource.java:73) at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:292) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:434) ... 64 more Caused by: java.lang.InstantiationException: tk.mybatis.mapper.provider.ExampleProvider at java.lang.Class.newInstance(Class.java:427) at org.apache.ibatis.builder.annotation.ProviderSqlSource.createSqlSource(ProviderSqlSource.java:85) ... 74 more Caused by: java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.ExampleProvider.<init>() at java.lang.Class.getConstructor0(Class.java:3082) at java.lang.Class.newInstance(Class.java:412) ... 75 more

spring mybatis集成,出错不回滚

配置文件,spring-servelt.xml <!-- 加载Controller --> <context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <!-- 启动对@AspectJ注解的支持 --> <aop:aspectj-autoproxy /> <!-- 手动注册AnnotationMethodHandlerAdapter,可以手动设置编码,解决使用ResponseBody返回数据时的中文乱码问题 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <!-- 这个配置需要spring 3.1支持,并增加 jackson-all-1.9.11.jar 解决springmvc返回json问题 --> <!-- jackson2 如果升级jackson为2.x版本,哪么需要更改下面的配置。MappingJackson2HttpMessageConverter --> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 下面这一行必须加,如果不加静态资源访问是正确,动态的访问就出错了 --> <mvc:annotation-driven /> <!-- 静态资源访问控制 --> <!-- <mvc:resources mapping="/WEB-INF/**" location="/WEB-INF/" /> --> <mvc:resources mapping="/images/**" location="/images/" /> <mvc:resources mapping="/control/**" location="/control/" /> 配置文件spring-config.xml <!-- 加载service --> <context:component-scan base-package="com"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <!-- 数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="connectionProperties" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@192.168.0.222:1521:orcl" /> <property name="username" value="framedb" /> <property name="password" value="qaz123" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value=" SELECT 1 FROM DUAL" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat" /> </bean> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.common.frame.login.model, com.common.frame.authorize.model, com.common.frame.organization.model, com.common.frame.security.model, com.common.frame.resourec.model" /> <!-- 此处不可以使用*号做通配符,如果想引入多个包,必须多次引入,使用“,”号分割 --> <!-- Pagehelper分页插件 开始 2015-3-31 ssx--> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageHelper"> <property name="properties"> <value> dialect=oracle reasonable=true params=count=countSql;pageSizeZero=zero </value> </property> </bean> </array> </property> <!-- Pagehelper分页插件 结束 --> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <property name="basePackage" value="com.common.frame.*.mapper" /> <!-- 此处可以使用*号做通配符 --> </bean> <!-- transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> <qualifier value="user" /> </bean> service方法 @Transactional(rollbackFor=Exception.class) public void getTest() { try { OrganModel organ = new OrganModel(); organ.setOrganId("11hh"); organ.setOrganCode("11hh"); organ.setOrganName("11hh"); organ.setOrganAbb("11hh"); organ.setIsUse("1"); organ.setCreateBy("111"); organ.setCreateTime("bbbb"); organMapper.insert(organ); OrganTypeModel organType = new OrganTypeModel(); organTypeMapper.insert(organType); } catch (RuntimeException e) { e.printStackTrace(); } } 执行到这个方法,本方法实现了两个插入,第一个插入没有问题通过,第二个插入报错,但第一个插入在报错之后未回滚。不知道为什么,请告知。谢谢

使用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一直为空,求大神指导下

Sping AOP 无法拦截父类方法的问题

各位好,我在项目中尝试使用SpringAOP拦截子类调用父类的方法,发现AOP无法切入到父类中,困惑许久,在网上寻了各种方法都没有解决,希望各位同行可以帮我指出其中的问题,不胜感激。 **子类:** ``` @Repository("userLoginDao") public class UserLoginDaoImpl extends BaseDao<UserLogin> implements IUserLoginDao{ @Override public UserLogin addUserlogin(UserLogin userLogin) { insertSelective(userLogin); return userLogin; } } ``` ** 父类: ** ``` public class BaseDao<E> extends SqlSessionDaoSupport { protected String daoName; private SqlSessionTemplate sqlSessionTemplate = null; @Autowired protected void setSessionTemplate(SqlSessionTemplate sessionTemplate) { super.setSqlSessionTemplate(sessionTemplate); this.sqlSessionTemplate = sessionTemplate; } @SuppressWarnings("unchecked") @PostConstruct protected void init() { ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass(); Class<E> daoType = (Class<E>) parameterizedType.getActualTypeArguments()[0]; this.daoName = "mapper."+ daoType.getName().substring(daoType.getName().lastIndexOf(".") + 1) + "Mapper."; } @InsertLog(description="添加") public int insertSelective(E bean) { return this.getSqlSession().insert(this.daoName + "insertSelective", bean); } } ``` ** AOP拦截器:** ``` @Aspect @Order(90) @Component public class ServiceLogAspect { private ThreadLocal<Map<String, Object>> serviceLocalMap = new ThreadLocal<Map<String, Object>>(); @Autowired private SqlSessionFactory sqlSessionFactory; //使用标签和匹配都试过不可以 // @Pointcut("@annotation(com.company.project.core.aoplog.InsertLog)") @Pointcut("execution(* com.company.project.service.user.base.BaseDao.insert*(..))") public void insertDaoAspect() { } // ----------------------------------对增加方法sql的记录 @Around("insertDaoAspect()") public Object insertDaoAspect(final ProceedingJoinPoint pjp) throws Throwable { Map<String, Object> map = serviceLocalMap.get(); // 获取操作的实体的类名 String modelName = null; Field fields[] = pjp.getTarget().getClass().getDeclaredFields();// 获得对象所有属性 for (Field field : fields) { field.setAccessible(true); if ("daoName".equals(field.getName())) { modelName = field.get(pjp.getTarget()).toString(); } } // 获取将要执行的sql语句所在Mapper String daoName = "mapper." + modelName + "Mapper."; Object obj = (pjp.getArgs().length > 0 ? pjp.getArgs()[0] : null);// 注意空指针异常 // 获取执行的修改sql语句 String sql = sqlSessionFactory.getConfiguration().getMappedStatement(daoName + pjp.getSignature().getName()) .getBoundSql(obj).getSql(); // 获取存储sql语句的列表 List<Map<String, Object>> listMap = (List<Map<String, Object>>) map.get("daoOperation"); if (listMap == null) { listMap = new ArrayList<Map<String, Object>>(); map.put("daoOperation", listMap); } Map<String, Object> daoMap = new HashMap<String, Object>(); listMap.add(daoMap); daoMap.put("daoMethodName", pjp.getTarget().getClass().getName() + "." + pjp.getSignature().getName()); daoMap.put("daoParameter", obj); daoMap.put("daoType", "添加"); daoMap.put("daoSql", sql.replaceAll("\n", "")); daoMap.put("start", System.currentTimeMillis()); Object value = pjp.proceed(); daoMap.put("return", value); daoMap.put("runTime", System.currentTimeMillis() - ((Long) daoMap.get("start"))); // 向卡夫卡发送日志信息 log.debug("-----------------//" + JSONObject.toJSONString(daoMap)); return value; // }else { // Object value = pjp.proceed(); // return value; // } } } ``` ** 自定义注解:** ``` @Target({ElementType.PARAMETER,ElementType.METHOD}) //ElementType.PARAMETER 方法参数,ElementType.METHOD 方法(表示这个注解是方法的注解) @Retention(RetentionPolicy.RUNTIME) //注解会在class字节码文件中存在,在运行时可以通过反射获取到 @Documented//说明该注解将被包含在javadoc中 public @interface InsertLog { String description() default ""; String versions() default ""; } ``` ** 主要配置 spring-base : ** <!-- 采用注释的方式配置bean --> <context:annotation-config /> <!-- 配置要扫描的包 --> <context:component-scan base-package="com.company.project" /> <!-- proxy-target-class默认"false",更改为"ture"使用CGLib动态代理 --> <aop:aspectj-autoproxy proxy-target-class="true" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:db.properties</value> <value>classpath:redis.properties</value> </list> </property> </bean> <import resource="classpath:spring/spring-dubbo-provider.xml" /> <import resource="classpath:spring/spring-mybatis.xml" /> <!-- <import resource="classpath:spring/spring-redis.xml" /> -->

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> ```

使用activeMQ监听,调用mapper时为null怎么解决,请大神帮忙看看

**spring文件配置如下:** <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/jms"> <context:annotation-config/> <context:component-scan base-package="com.lizx" /> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <!-- 定义事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 定义事务策略 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--所有以query开头的方法都是只读的 --> <tx:method name="query*" read-only="true" /> <tx:method name="get*" read-only="true" /> <!--其他方法使用默认事务策略 --> <tx:method name="delete*" propagation="REQUIRED" read-only="false"/> <tx:method name="edit*" propagation="REQUIRED" read-only="false"/> <tx:method name="add*" propagation="REQUIRED" read-only="false"/> </tx:attributes> </tx:advice> <aop:config> <!--pointcut元素定义一个切入点,execution中的第一个星号 用以匹配方法的返回类型, 这里星号表明匹配所有返回类型。 com.bw.service.*.*(..)表明匹配com.bw.service包下的所有类的所有 方法 --> <aop:pointcut id="myPointcut" expression="execution(* com.lizx.app.service.*.*(..))" /> <!--将定义好的事务处理策略应用到上述的切入点 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" /> </aop:config> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 加载mybatis.cfg.xml文件 --> <property name="configLocation" value="classpath:conf/SqlMapConfig.xml"></property> <!-- 自动扫描需要定义类别名的包,将包内的JAVA类的类名作为类别名 --> <property name="typeAliasesPackage" value="com.lizx.app"></property> </bean> <!-- 自动扫描所有的Mapper接口与文件 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.lizx.app.mapper"></property> </bean> <import resource="classpath*:conf/spring-ActiveMQ.xml" /> </beans> ------------------------------------ **activemq配置如下:** <?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:amq="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms" 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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.1.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"> <mvc:annotation-driven /> <amq:connectionFactory id="amqConnectionFactory" brokerURL="tcp://127.0.0.1:61616" userName="admin" password="admin" /> <!-- 配置JMS连接工长 --> <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory"> <constructor-arg ref="amqConnectionFactory" /> <property name="sessionCacheSize" value="100" /> </bean> <!-- 定义消息队列(Queue) --> <bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue"> <!-- 设置消息队列的名字 --> <constructor-arg> <value>Jaycekon</value> </constructor-arg> </bean> <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 --> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <property name="defaultDestination" ref="demoQueueDestination" /> <property name="receiveTimeout" value="10000" /> <!-- true是topic,false是queue,默认是false,此处显示写出false --> <property name="pubSubDomain" value="false" /> </bean> <!-- 配置消息队列监听者(Queue) --> <bean id="queueMessageListener" class="com.lizx.app.MQListener" /> <bean id="queueListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="connectionFactory" /> <property name="destination" ref="demoQueueDestination" /> <property name="messageListener" ref="queueMessageListener" /> </bean> </beans> ------------------------------------ **在监听中使用为null时的情况** ![图片说明](https://img-ask.csdn.net/upload/201802/25/1519561067_682041.png) **在其它地方调用,不为null时的情况:** ![图片说明](https://img-ask.csdn.net/upload/201802/25/1519561131_923727.png)

SSM配置applicationContext.xml中mybatis的bean出现问题

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:230) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) 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:191) 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 'sqlSessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\01Web\ssm-crud\target\classes\mapper\DepartmentMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for mapper.DepartmentMapper.BaseResultMap at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) 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:742) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251) 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.core.NestedIOException: Failed to parse mapping resource: 'file [D:\01Web\ssm-crud\target\classes\mapper\DepartmentMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for mapper.DepartmentMapper.BaseResultMap at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:466) at org.mybatis.spring.SqlSessionFactoryBean.afterPropertiesSet(SqlSessionFactoryBean.java:340) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ... 40 more Caused by: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for mapper.DepartmentMapper.BaseResultMap at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:120) at org.apache.ibatis.builder.xml.XMLMapperBuilder.parse(XMLMapperBuilder.java:92) at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:464) ... 43 more Caused by: java.lang.IllegalArgumentException: Result Maps collection already contains value for mapper.DepartmentMapper.BaseResultMap at org.apache.ibatis.session.Configuration$StrictMap.put(Configuration.java:859) at org.apache.ibatis.session.Configuration$StrictMap.put(Configuration.java:831) at org.apache.ibatis.session.Configuration.addResultMap(Configuration.java:613) at org.apache.ibatis.builder.MapperBuilderAssistant.addResultMap(MapperBuilderAssistant.java:214) at org.apache.ibatis.builder.ResultMapResolver.resolve(ResultMapResolver.java:47) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:285) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElement(XMLMapperBuilder.java:252) at org.apache.ibatis.builder.xml.XMLMapperBuilder.resultMapElements(XMLMapperBuilder.java:244) at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:116) ... 45 more 这是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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- Spring的配置文件,这里主要配置和业务逻辑有关的 --> <!--=================== 数据源,事务控制,xxx ================--> <context:property-placeholder location="classpath:dbconfig.properties" /> <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- ===============事务控制的配置 ================--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--控制住数据源 --> <property name="dataSource" ref="pooledDataSource"></property> </bean> <!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式) --> <aop:config> <!-- 切入点表达式 --> <aop:pointcut expression="execution(* com.atguigu.crud.service..*(..))" id="txPoint"/> <!-- 配置事务增强 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <!--配置事务增强,事务如何切入 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 所有方法都是事务方法 --> <tx:method name="*"/> <!--以get开始的所有方法 --> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> <!--================== 配置和MyBatis的整合=============== --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定mybatis全局配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <!-- 指定mybatis,mapper文件的位置 --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--扫描所有dao接口的实现,加入到ioc容器中 --> <property name="basePackage" value="com.atguigu.crud.dao"></property> </bean> <!-- 配置一个可以执行批量的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </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="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <package name="com.atguigu.crud.bean"/> </typeAliases> </configuration> 位置:

Springmvc-myBatis配置文件不解析数据库的properties文件

初次配置SpringMVC+myBatis,使用properties来存储数据库的相关数据,并在xml中读取出来,写入dataSource中。 这时发现报错:Cannot load JDBC driver class ${jdbc.driverClassName} java.lang.ClassNotFoundException: ${driverClass} 按理说没有jar包,应该报错Cannot load JDBC driver class com.mysql.jdbc.Drive ``` <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClass}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> ``` 如果像上述这样就会报错,properties文件无误。 如果改成这样: ``` <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/Lettiy"/> <property name="username" value="root"/> <property name="password" value="root"/> ``` 便可以正常访问,所以怀疑时properties文件没有正常导入 在xml最开始已经引入了该properties,路径正确,可以通过ctrl直接打开 ``` <context:property-placeholder location="classpath:jdbc.properties"/> ``` 现在贴出全部的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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/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"> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 扫描注解Bean --> <context:component-scan base-package="*.service"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 开启AOP监听 只对当前配置文件有效 --> <aop:aspectj-autoproxy expose-proxy="true"/> <!--myBatis 配置--> <!-- 第一种方式:加载一个properties文件 --> <!--<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">--> <!--<property name="location" value="classpath:resource/jdbc.properties"/>--> <!--</bean>--> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClass}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </bean> <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-spring.xml" /> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:datamapper/**/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="login.repository"/> <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> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <tx:annotation-driven transaction-manager="transactionManager"/> <!--repository 注解扫描--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="annotationClass" value="org.springframework.stereotype.Repository"/> <property name="basePackage" value="login.repository"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans> ```

Springboot启动报错 一个是找不到url 一个是找不到dao

## 之前一直启动都没有问题,今天突然发现启动不了 ![图片说明](https://img-ask.csdn.net/upload/201910/10/1570671612_490949.jpg) ## 然后我把启动的位置改成@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) ``` package com.mall.shopping.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; /*@SpringBootApplication*/ @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` ## 然后会报新的错: ![图片说明](https://img-ask.csdn.net/upload/201910/10/1570671806_766601.jpg) # 到现在没找到新错误的原因 还是在报找不到dao的错误。 ## 实体类代码: ![图片说明](https://img-ask.csdn.net/upload/201910/10/1570672651_585106.jpg) ## controller代码: ``` package com.mall.shopping.demo.controller; import com.mall.shopping.demo.services.UserService; import com.mall.shopping.demo.vo.Huser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Iterator; import java.util.List; @Controller public class UserController { @Autowired private UserService userService; @RequestMapping("/tiao") public ModelAndView zhuan() { ModelAndView modelAndView = new ModelAndView("loginindex"); return modelAndView; } @RequestMapping("/tiao1") public ModelAndView zhuan1() { ModelAndView modelAndView = new ModelAndView("adminindex"); return modelAndView; } @RequestMapping("/Userlogin") public String userlogin(HttpServletRequest request, HttpServletResponse response) { String username = (String) request.getParameter("username"); String userpwd = (String)request.getParameter("userpwd"); List<Huser> huser = userService.userlogin(); Iterator iter = huser.iterator(); while(iter.hasNext()){ Huser ha = (Huser) iter.next(); if(username.equals(ha.getHuser())) { if(userpwd.equals(ha.getHpwd())) { return "redirect:/tiao1"; } else { return "redirect:/tiao"; } } } return "redirect:/tiao"; } } ``` ## services代码: ``` package com.mall.shopping.demo.services; import com.mall.shopping.demo.dao.UserDao; import com.mall.shopping.demo.vo.Huser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserDao userDao; public List<Huser> userlogin(){ return userDao.userlogin();} } ``` ## daoceng代码: ``` package com.mall.shopping.demo.dao; import com.mall.shopping.demo.vo.Huser; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; @Repository @Mapper public interface UserDao { List<Huser>userlogin(); } ``` ## mybatitsconfig: ``` <?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> <!-- 开启驼蜂标识:last_name lastName --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- 实体Bean别名 --> <typeAliases> <package name="com.mall.shopping.demo.vo.Huser"/> <package name="com.mall.shopping.demo.vo.Hdaohang"/> </typeAliases> <mappers> <mapper resource="mapper/select-login.xml"/> <mapper resource="mapper/select-hdaohang.xml"/> </mappers> </configuration> ``` ## 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.mall.shopping.demo.dao.UserDao"> <resultMap id="SelectLogin" type="com.mall.shopping.demo.vo.Huser"> <id property="hid" column="HID"></id> <result property="huser" column="HUSER"></result> <result property="hpwd" column="HPWD"></result> </resultMap> <select id="userlogin" resultMap="SelectLogin"> select * from huser </select> </mapper> ``` ## application.properties ``` server.port=8083 server.address=127.0.0.1 #server.session-timeout=60 spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl spring.datasource.username=scott spring.datasource.password=tiger spring.datasource.driver-class-name=oracle.jdbc.OracleDriver mybatis.mapperLocations=classpath:mapper/*.xml mybatis.config-locations=classpath:mybatis/mybatis-config.xml spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp ``` ## pom文件: ``` <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mall.shopping</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <spring.version>5.1.5.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.4.5</mybatis.version> <!-- oracle驱动版本号 --> <oracle-driver.version>11.2.0</oracle-driver.version> <!-- log4j日志包版本号 --> <slf4j.version>1.7.18</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 添加spring核心库 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- 添加mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- oracle驱动依赖 --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>${oracle-driver.version}</version> </dependency> <!-- dbcp,用来在spring-mybatis.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.12</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.12</version> </dependency> <dependency> <groupId>org.xmlunit</groupId> <artifactId>xmlunit-core</artifactId> </dependency> <!-- <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency>--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!--用于编译jsp --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!--添加热部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!--热部署配置--> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!--fork:如果没有该项配置,整个devtools不会起作用--> <fork>true</fork> </configuration> </plugin> <!-- <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> <versionRange>[1.2,)</versionRange> <goals> <goal>enforce</goal> </goals> </pluginExecutionFilter> <action> <ignore /> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin>--> <!--mybatis 逆向工程插件--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <executions> <execution> <id>Generate MyBatis Artifacts</id> <goals> <goal>generate</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>${oracle-driver.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> </dependencies> </plugin> </plugins> <!-- <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources>--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project> ``` ## 目录结构: ![图片说明](https://img-ask.csdn.net/upload/201910/10/1570672730_102043.jpg)

mybatis insert插入语句以后 一直报错怎么回事 怎么在保存以后获取保存对象的id

项目采用的框架是springmvc mybatis 数据库 mysql 控制器代码: 还有怎么在保存一一张表的同时 保存到另一张表 把A表的id 保存到B表(关联的表) ``` List<EarDiseaseSwtj> listEdSwtj=earStudyService.findEdByid(id1); if (listEdSwtj.size() != 0) { //int num2 = earDisease100Service.updateEdSwtj(id1, name, desc);// 修改的仅是ear_disease_100这个表 int num2=earStudyService.updateEdSwtj(id1, name, desc); if (num2 != 0) { request.setAttribute("ok", "修改成功"); } return "manage/forJsp.do?&requestType=17&num1=" + currentPageNum1; } else { //earStudyService.saveEdSwtj(id1, name, desc); earStudyService.saveEdSwtj(name, desc); request.setAttribute("ok", "添加成功"); return "manage/forJsp.do?&requestType=17&num1=" + currentPageNum1; } } ``` mybatis sql如下: ``` <insert id="saveEd" parameterType="EarDiseaseSwtj"> insert into dt_ear_disease_swtj (name,desc) values (#{name},#{desc}) </insert> ``` 报错代码如下: ``` HTTP Status 500 - Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: type Exception report message Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: description The server encountered an internal error that prevented it from fulfilling this request. exception org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'desc) values ('qqqe','eqeqe')' at line 2 ### The error may involve com.app.dao.mapper.EarDiseaseSwtjMapper.saveEd-Inline ### The error occurred while setting parameters ### SQL: insert into dt_ear_disease_swtj (name,desc) values (?,?) ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'desc) values ('qqqe','eqeqe')' at line 2 ; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'desc) values ('qqqe','eqeqe')' at line 2 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) javax.servlet.http.HttpServlet.service(HttpServlet.java:650) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) root cause org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'desc) values ('qqqe','eqeqe')' at line 2 ### The error may involve com.app.dao.mapper.EarDiseaseSwtjMapper.saveEd-Inline ### The error occurred while setting parameters ### SQL: insert into dt_ear_disease_swtj (name,desc) values (?,?) ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'desc) values ('qqqe','eqeqe')' at line 2 ; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'desc) values ('qqqe','eqeqe')' at line 2 org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:233) org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:71) org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:365) sun.proxy.$Proxy10.insert(Unknown Source) org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:237) org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:79) org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:40) sun.proxy.$Proxy39.saveEd(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) sun.proxy.$Proxy40.saveEd(Unknown Source) com.app.dao.impl.EarDiseaseSwtjDaoImpl.saveEd(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) sun.proxy.$Proxy41.saveEd(Unknown Source) com.app.service.impl.EarStudyServiceImpl.saveEdSwtj(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) sun.proxy.$Proxy99.saveEdSwtj(Unknown Source) com.app.totalController.ManageController.forJsp(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:427) org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:415) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:788) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:717) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) javax.servlet.http.HttpServlet.service(HttpServlet.java:650) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) root cause ```

spring加mybatis的事务配置,我如果不加事务方法是可以执行的,配置了事务没效果

``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://${datasource.cloudx.host}:${datasource.cloudx.port}/${datasource.cloudx.database}?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;allowMultiQueries=true" /> <property name="username" value="${datasource.cloudx.user}" /> <property name="password" value="${datasource.cloudx.password}" /> <property name="initialSize" value="5" /> <property name="maxActive" value="50" /> <property name="maxIdle" value="50" /> <property name="minIdle" value="5" /> <property name="maxWait" value="30000" /> <property name="validationQuery" value="SELECT 1+1" /> <property name="defaultAutoCommit" value="false" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:conf-mybatis/mybatis-base.xml" /> <property name="mapperLocations" value="classpath*:conf-mybatis/mybatis-mapper-*.xml" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="iccardTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="iccardTerm" expression="execution(public * com.cessas.cloudx.service.*.*(..))" /> <aop:advisor pointcut-ref="iccardTerm" advice-ref="iccardTxAdvice" /> </aop:config> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` ```这个是spring_aop的配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <aop:aspectj-autoproxy /> </beans> ```

spring mvc+mybatis 事务控制不起作用

用的是spring mvc和mybatis框架。数据库是mysql。然后发现事务配置了不起作用。。业务逻辑是新增用户,用户新增成功之后再在其他表插入一条对应的用户角色关联信息。现在问题是假如用户插入成功之后。。插入对应的用户角色关联信息出错后,用户那条新增记录不能自动删除。看了很多人说是因为@service提前扫描的问题。那个我改过了。还有说是表的引擎不是InnoDB。但是我们建的表是InnoDB。还有说要抛出RuntimeException。我也抛出了。。但是还是没用。没办法。请大家看下: -serlet.xml: [code="xml"] <mvc:resources mapping="/resources/**" location="/resources/" /> <context:annotation-config /> <mvc:annotation-driven /> <!-- ①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="com.xuanyan.uebuycar.*"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="cacheSeconds" value="0" /> <property name="webBindingInitializer"> <bean class="com.xuanyan.uebuycar.admin.util.WebDataBinder4DateAndTime"/> </property> </bean> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".html"/> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="i18n/messages"/> [/code] applicationContext.xml: [code="xml"] <!-- 用于持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的静态方法得到spring bean对象 --> <bean class="com.xuanyan.uebuycar.admin.util.SpringContextHolder" lazy-init="false" /> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="proxool" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- 数据连接事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="proxool" /> </bean> <!-- 不扫描带有@Controller注解的类。因为这些类已经随容器启动时,在servlet-context中扫描过一遍了 --> <context:component-scan base-package="com.xuanyan.uebuycar"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 激活annotation功能 --> <context:annotation-config /> <!-- 激活annotation功能 --> <context:spring-configured/> <!-- mybatis接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xuanyan.uebuycar.admin.dao" /> </bean> <!-- 连接事务的注解配置 --> <tx:annotation-driven transaction-manager="transactionManager" /> <aop:config proxy-target-class="true"> <aop:pointcut id="fooServiceOperation" expression="execution(* com.xuanyan.uebuycar.admin.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- the transactional semantics... --> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception" /> <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> [/code] 方法: [code="java"] public String addOrUpdate(SysUser record,SysUser currUser,String actionType,String roleId){ String str=getDefJsonString(false, "操作失败,请稍后再试!"); try { if(record!=null){ Date now=new Date(); SysUserExample example=new SysUserExample(); example.createCriteria().andUserCodeEqualTo(record.getUserCode()); List<SysUser> list=sysUserMapper.selectByExample(example); if("add".equalsIgnoreCase(actionType)){ if(list!=null&&list.size()>0){ str=getDefJsonString(false, "操作失败,该账号已存在!"); return str; } String userId=CommonUtil.getUUIDString(); record.setUserId(userId); record.setUserPassword(CommonUtil.getMD5Str(SystemCommonParam.DEFAULT_USER_PWD)); record.setUpdateUser(currUser.getUserCode()); record.setUpdateTime(now); if(sysUserMapper.insertSelective(record)>0){ SysRoleUser ru=new SysRoleUser(); // ru.setRoleUserId(CommonUtil.getUUIDString()); ru.setRoleId(roleId); ru.setUserId(userId); ru.setUpdateUser(currUser.getUserCode()); ru.setUpdateTime(now); if(sysRoleUserMapper.insertSelective(ru)>0){ str=getDefJsonString(true, "新增成功!"); } } }else if("edit".equalsIgnoreCase(actionType)){ if(list!=null&&list.size()>0){ if(!list.get(0).getUserId().equals(record.getUserId())){ str=getDefJsonString(false, "操作失败,该账号已存在!"); return str; } } record.setUpdateUser(currUser.getUserCode()); record.setUpdateTime(now); if(sysUserMapper.updateByPrimaryKeySelective(record)>0){ SysRoleUser ru=new SysRoleUser(); ru.setRoleId(roleId); SysRoleUserExample ex=new SysRoleUserExample(); ex.createCriteria().andUserIdEqualTo(record.getUserId()); if(sysRoleUserMapper.updateByExampleSelective(ru, ex)>0){ str=getDefJsonString(true, "修改成功!"); } } } } } catch (Exception e) { str=getDefErrorString(); e.printStackTrace(); throw new RuntimeException(); } return str; } [/code] 类路径:com.xuanyan.uebuycar.admin.services.sys.SysUserService 希望各位有知道能够告知一下。。是不是我service方法写的不对?

使用junit测试springMVC和mybatis项目出现autowired field

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cn.com.qzinfo.test.example.ExampleDaoTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.com.qzinfo.example.dao.ExampleDao cn.com.qzinfo.test.example.ExampleDaoTest.exampleDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [cn.com.qzinfo.example.dao.ExampleDao] 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:286) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1064) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41) at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:220) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.com.qzinfo.example.dao.ExampleDao cn.com.qzinfo.test.example.ExampleDaoTest.exampleDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [cn.com.qzinfo.example.dao.ExampleDao] 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:507) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:283) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [cn.com.qzinfo.example.dao.ExampleDao] 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:903) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:772) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:686) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478) ... 28 more 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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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" default-autowire="byName"> <!-- 强制使用CGLIB --> <aop:aspectj-autoproxy proxy-target-class="true" /> <!-- 数据源mysql --> <bean id="mysql-DataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql:///springmvc" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <!-- spring ibatis SqlMapClient --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="classpath:sqlmap-config.xml" /> <property name="dataSource" ref="mysql-DataSource" /> </bean> <!-- 事务管理DataSourceTranSactionManager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="mysql-DataSource" /> </bean> <!-- 启动spring注解功能 --> <tx:annotation-driven transaction-manager="transactionManager" /> <aop:aspectj-autoproxy /> </beans> 测试类文件: package cn.com.qzinfo.test.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.com.qzinfo.example.dao.ExampleDao; import cn.com.qzinfo.example.model.Example; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class ExampleDaoTest{ @Autowired private ExampleDao exampleDao; @Test public void test() { Example example =new Example(); example.setOperatorId(111); example.setIntRev1(111); exampleDao.insert(example); } }

spring中加入AOP事务报错

<?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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- Spring的配置文件,这里主要配置和业务逻辑有关的 --> <!--=================== 数据源,事务控制,xxx ================--> <context:property-placeholder location="classpath:dbconfig.properties" /> <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--================== 配置和MyBatis的整合=============== --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定mybatis全局配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <!-- 指定mybatis,mapper文件的位置 --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--扫描所有dao接口的实现,加入到ioc容器中 --> <property name="basePackage" value="com.atguigu.crud.dao"></property> </bean> <!--============================================= --> <!-- ===============事务控制的配置 ================--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--控制住数据源 --> <property name="dataSource" ref="pooledDataSource"></property> </bean> <!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式) --> <aop:config> <!-- 切入点表达式 --> <aop:pointcut expression="execution(* com.atguigu.crud.service..*(..))" id="txPoint"/> <!-- 配置事务增强 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <!--配置事务增强,事务如何切入 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 所有方法都是事务方法 --> <tx:method name="*"/> <!--以get开始的所有方法 --> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> <!-- Spring配置文件的核心点(数据源、与mybatis的整合,事务控制) --> </beans>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Intellij IDEA 实用插件安利

1. 前言从2020 年 JVM 生态报告解读 可以看出Intellij IDEA 目前已经稳坐 Java IDE 头把交椅。而且统计得出付费用户已经超过了八成(国外统计)。IDEA 的...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

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

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

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

魂迁光刻,梦绕芯片,中芯国际终获ASML大型光刻机

据羊城晚报报道,近日中芯国际从荷兰进口的一台大型光刻机,顺利通过深圳出口加工区场站两道闸口进入厂区,中芯国际发表公告称该光刻机并非此前盛传的EUV光刻机,主要用于企业复工复产后的生产线扩容。 我们知道EUV主要用于7nm及以下制程的芯片制造,光刻机作为集成电路制造中最关键的设备,对芯片制作工艺有着决定性的影响,被誉为“超精密制造技术皇冠上的明珠”,根据之前中芯国际的公报,目...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

百度工程师,获利10万,判刑3年!

所有一夜暴富的方法都写在刑法中,但总有人心存侥幸。这些年互联网犯罪高发,一些工程师高技术犯罪更是引发关注。这两天,一个百度运维工程师的案例传遍朋友圈。1...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

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

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

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

实时更新:计算机编程语言排行榜—TIOBE世界编程语言排行榜(2020年6月份最新版)

内容导航: 1、TIOBE排行榜 2、总榜(2020年6月份) 3、本月前三名 3.1、C 3.2、Java 3.3、Python 4、学习路线图 5、参考地址 1、TIOBE排行榜 TIOBE排行榜是根据全世界互联网上有经验的程序员、课程和第三方厂商的数量,并使用搜索引擎(如Google、Bing、Yahoo!)以及Wikipedia、Amazon、YouTube统计出排名数据。

立即提问
相关内容推荐