spring +springmvc+mybatis,service中调用dao接口报空

搭建ssm,启动项目没问题,但是在service实现类中调用dao接口时,对象loginDao对象是空的,错误信息如下

图片说明
log4j:ERROR Error occured while converting date.
java.lang.NullPointerException
at java.lang.System.arraycopy(Native Method)
at java.lang.AbstractStringBuilder.getChars(Unknown Source)
at java.lang.StringBuffer.getChars(Unknown Source)
at org.apache.log4j.helpers.ISO8601DateFormat.format(ISO8601DateFormat.java:130)
at java.text.DateFormat.format(Unknown Source)
at org.apache.log4j.helpers.PatternParser$DatePatternConverter.convert(PatternParser.java:443)
at org.apache.log4j.helpers.PatternConverter.format(PatternConverter.java:65)
at org.apache.log4j.PatternLayout.format(PatternLayout.java:506)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:310)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:162)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
at org.apache.log4j.Category.callAppenders(Category.java:206)
at org.apache.log4j.Category.forcedLog(Category.java:391)
at org.apache.log4j.Category.log(Category.java:856)
at org.apache.commons.logging.impl.Log4JLogger.debug(Log4JLogger.java:177)
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:132)
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1148)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:985)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:917)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:824)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:798)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

9个回答

loginDao要用注解赋值。

这是控制台报的错误信息,指向的就是service实现类中调用dao接口的方法

2015-12-27 18:28:40,374 [http-8080-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request
java.lang.NullPointerException
at com.zj.service.impl.LoginServiceImpl.find(LoginServiceImpl.java:27)
at com.zj.controller.LoginController.testLogin2(LoginController.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:917)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:824)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:798)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

http://ask.csdn.net/questions/228070
这个地址可以看见其他配置文件的内容

建议楼主逐层向下排查,看一下在哪个位置没有获取到id的值

u010690143
不会写代码的程序员 谢谢。我总共只有3层,debug发现service实现类的loginDao对象是空的,怀疑是没有注入到容器中,但是不知道怎么改
4 年多之前 回复
u010690143
不会写代码的程序员 谢谢。我总共只有3层,debug发现service实现类的loginDao对象是空的,怀疑是没有注入到容器中,但是不知道怎么改
4 年多之前 回复

估计配置文件的问题。发个看看

估计配置文件的问题。发个看看

楼主你的service中的dao是通过配置文件注入的么。。看你贴的图里没有@autowired啊。。

你要是用注解方式注入,那就是缺少@autowired,如果是通过xml配置文件配置,那就贴下配置文件~~~~

看你的spring配置文件中使用了注解注入的方式,但是在service中loginDao对象没有加上自动注入的注解即@Autowired

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring +springmvc+mybatis,service中调用dao接口报空

搭建ssm,启动项目没问题,但是在service实现类中调用dao接口时,对象loginDao对象是空的,错误信息如下 ![图片说明](https://img-ask.csdn.net/upload/201512/27/1451212017_76737.png) log4j:ERROR Error occured while converting date. java.lang.NullPointerException at java.lang.System.arraycopy(Native Method) at java.lang.AbstractStringBuilder.getChars(Unknown Source) at java.lang.StringBuffer.getChars(Unknown Source) at org.apache.log4j.helpers.ISO8601DateFormat.format(ISO8601DateFormat.java:130) at java.text.DateFormat.format(Unknown Source) at org.apache.log4j.helpers.PatternParser$DatePatternConverter.convert(PatternParser.java:443) at org.apache.log4j.helpers.PatternConverter.format(PatternConverter.java:65) at org.apache.log4j.PatternLayout.format(PatternLayout.java:506) at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:310) at org.apache.log4j.WriterAppender.append(WriterAppender.java:162) at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251) at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66) at org.apache.log4j.Category.callAppenders(Category.java:206) at org.apache.log4j.Category.forcedLog(Category.java:391) at org.apache.log4j.Category.log(Category.java:856) at org.apache.commons.logging.impl.Log4JLogger.debug(Log4JLogger.java:177) at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:132) at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1148) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:985) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:917) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:824) at javax.servlet.http.HttpServlet.service(HttpServlet.java:643) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:798) at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source)

SpringMVC mybatis注入Dao层失败

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

springMVC+myBatis中如何进行事务处理

springMVC+myBatis中在使用注解方式的时候如何进行事务处理

springmvc+mybatis中的使用Dao查询失败

service代码: // 查询每一列的空值 public List<TljsjkAjlj27> findNullCount() { return dao.findNullCount();//查询失败 } Dao代码: @MyBatisDao public interface TljsjkAjlj27Dao extends CrudDao<TljsjkAjlj27> { public List<TljsjkAjlj27> findNullCount(); } mybaitsi的Mapping映射文件: <mapper namespace="com.jiahe.bigdata.bd.dao.TljsjkAjlj27Dao"> <resultMap id="BaseResultMap" type="com.jiahe.bigdata.bd.entity.TljsjkAjlj27"> xxxxxxxxxxxxxxx xxxxxxxxxxxxxxx </resultMap> <select id="findNullCount" resultMap="BaseResultMap"> SELECT (SELECT count(*) FROM T_LJSJK_AJLJ27 WHERE DW IS NULL) DW , (SELECT count(*) FROM T_LJSJK_AJLJ27 WHERE JH IS NULL) JH , (SELECT count(*) FROM T_LJSJK_AJLJ27 WHERE JHDM IS NULL) JHDM , (SELECT count(*) FROM T_LJSJK_AJLJ27 WHERE JSCH IS NULL) JSCH , (SELECT count(*) FROM T_LJSJK_AJLJ27 WHERE XH IS NULL) XH , (SELECT count(*) FROM T_LJSJK_AJLJ27 WHERE CW IS NULL) CW FROM SYSIBM.SYSDUMMY1 </select> </mapper> 如上所述,service的查询失败,请问这是什么愿意造成的? 说明:我更改过这张映射文件的方法名id值,对其Dao及其service也做相应调整,无误。另外有一张表跟这个表类型,java的代码及其映射文件配置也类似,另外一张的Dao查询成功,而这张表却失败。 请教各位大咖,希望各位不灵赐教,跪谢!!!

spring中service层中无法autowired注入dao,报空指针异常,求助各位大神

## controller代码: @Controller public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/add.action") public String add(Model model) throws Exception { userService.add(); System.out.println("controller............"); return "/WEB-INF/jsp/1.jsp"; } } ## service代码 public class UserService { @Autowired private UserDaoImpl userDao; public void add() throws Exception { userDao.add(); System.out.println("service.............."); } } ## dao代码 @Repository public class UserDaoImpl{ public void add() throws Exception { System.out.println("daoImpl.............."); } } ## 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" 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"> <!--<context:component-scan base-package="cn.taxas.spring.dao"/>--> <bean id="userDao" class="cn.taxas.spring.dao.UserDaoImpl"/> <bean id="userService" class="cn.taxas.spring.service.UserService"/> </beans> ## springmvc配置文件; <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <mvc:annotation-driven/> <context:component-scan base-package="cn.taxas.spring.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--<bean id="userController" class="cn.taxas.spring.controller.UserController"/>--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/> </beans> ## 报错: java.lang.NullPointerException at cn.taxas.spring.service.UserService.add(UserService.java:20) at cn.taxas.spring.controller.UserController.add(UserController.java:23) at sun.reflect.GeneratedMethodAccessor42.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)

spring @Autowired service dao装配顺序?

代码结构如下: @Controller public class MyController{ @Autowired private MyService service; } @Service public class MyService{ @Autowired private MyFirstDao myFirstDao; public void check(Integer id) { //调用baseDao中基本的查询entity的方法 myFirstDao.find(id);//此处myFirstDao==null 为什么?? } } @Repository public class MyFirstDao extends BaseDao<FirstEntity>{//FirstEntity extends BaseEntity } @Repository public class MySecondDao extends BaseDao<SecondEntity>{//SecondEntity extends BaseEntity } public class BaseDao<T extends BaseEntity>{ //实现基本的增删改查 public void find(){} public void del(){} public void add(){} } 按照我的理解,在初始化controller时会自动注入service(即完成service的初始化并获一个实例对象),同时因为service中有用@Autowired标注MyFirstDao ,因此会同时给serivce注入myFirstDao才对,为什么myFirstDao没注入成功呢?获取到的dao为null。 此种场景下,要调用基本的baseDao中的查询方法应该如何解决呢? 注: 其他xml中的配置都没问题。 急求解答。初学者对spring机制不是特别熟悉。

我用的是spring mvc+mybatis,问一下service层应该都需要写什么

我想问一下service层,dao层,control层都应该写什么? 我们项目经理说 service层只要写一个dao引用,service和表是一一对应的, 我觉得service既然是业务层是不是所有业务相关的都要写? 比如学生,班级,成绩三个表 我们现在是对应学生表有一个增删改查的dao和service, 对应班级表有一个增删改查的dao和service, 对应成绩表有一个增删改查的dao和service, 如果查询及格的学生的班级和姓名 是不是要在学生control里调用成绩和班级的service? 还是在学生service实现类里调用成绩和班级的service来获得结果呢? 真不知道代码规范是什么。求有经验的大神详细讲解一下谢谢了

在java timer定时器中调用dao层会报错

现在在做一个web项目,使用spring+springMVC+hibernate框架, 问题描述: 项目中有一个扫描的功能,分即时任务、定时任务、周期任务三种,即时任务已经实现了,现在使用java.util.Timer、java.util.TimerTask类做定时任务,重写TimerTask的run方法,在run方法中调用之前已经没有问题的即时任务扫描方法。每次运行定时任务时,会卡在dao层方法的调用上,因为在即时任务的扫描方法中调用了dao层的数据操作方法,报错“No Session found for current thread”。 即时任务的执行流程:前台提交即时任务扫描请求->控制器调用service层的立即扫描方法startImmediateTask(); 定时任务的执行流程:前台提交定时任务扫描请求->控制器调用service层的定时扫描方法startTimerTask()->调用立即扫描方法startImmediateTask()。 下面附上代码和配置文件,请各位大牛帮忙解决啊! service层代码 ```java /** * 开始定时扫描任务 * @param blTask */ public void startTimerTask(final BLTask blTask) { Date startDate = blTask.getStartTime(); TimerTask task = new TimerTask() { @Override public void run() { // 调用扫描方法 startImmediateTask(blTask); } }; Timer timer = new Timer(); timer.schedule(task, startDate); } /** * 开始即时扫描任务 * @param blTask */ public void startImmediateTask(BLTask blTask) { BLScanParam blScanParam = new BLScanParam(); BLPolicyGroup blPolicyGroup = null; // 策略组 List<BLCheckItem> blCheckItems = null; // 检查项 Map<Long, BLCheckScript> blCheckScriptMap = new HashMap<Long, BLCheckScript>(); // 检查脚本 Long pgId = null; // 策略组ID String alias = null; // 策略别名、检查项别名 Long osType = blTask.getOsType(); // 操作系统类型 List<Long> csIds = new ArrayList<Long>(); // 检查脚本ID数组 blScanParam.setBlTask(blTask); pgId = blTask.getPgId(); // 通过策略组ID查找策略组 blPolicyGroup = blPolicyGroupDao.get(pgId); if (blPolicyGroup == null) { return; } blScanParam.setBlPolicyGroup(blPolicyGroup); alias = blPolicyGroup.getAlias(); // 通过别名、操作系统类别查找所有匹配的检查项 blCheckItems = blCheckItemDao.queryByProerties(new String[]{"alias", "osType"}, new Object[]{alias, osType}); if (blCheckItems == null || blCheckItems.size() <= 0) { return; } blScanParam.setBlCheckItems(blCheckItems); for (BLCheckItem blCheckItem : blCheckItems) { csIds.add(blCheckItem.getCsId()); } int size = csIds.size(); // 获取当前策略组下的所有检查项的检测脚本 List<BLCheckScript> blCheckScripts = blCheckScriptDao.queryByProerties("csId", (Long[])csIds.toArray(new Long[size])); for (BLCheckScript blCheckScript : blCheckScripts) { // 获取当前策略组下的所有检测脚本,并放入map中 blCheckScriptMap.put(blCheckScript.getCsId(), blCheckScript); } blScanParam.setBlCheckScriptMap(blCheckScriptMap); // 分割ip为数组,传入TaskDispatch String[] ips = getIps(blTask.getIpArea()); TaskDispatch taskDispatch = new TaskDispatch(ips, blScanParam); taskDispatch.StartTask(); // 将当前TaskDispatch对象的引用放入taskDispatchMap中,供停止任务时使用 taskDispatchMap.put(blTask.getTkId(), taskDispatch); } ``` BaseDao的部分代码 ```java public class BaseDao<E> implements Dao<E> { public SessionFactory getSessionFactory() { return this.sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { return this.sessionFactory.getCurrentSession(); } @Resource(name = "sessionFactory") public void setSF(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } } ``` applicationContext.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <context:annotation-config /> <context:component-scan base-package="com.djbh" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://192.168.1.247:3306/djbh_db?useUnicode=true&amp;characterEncoding=utf-8" /> <property name="user" value="root" /> <property name="password" value="mysql" /> <!-- <property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;DatabaseName=DJBH_DB" /> <property name="user" value="sa" /> <property name="password" value="123456" /> --> <property name="acquireIncrement" value="3" /> <property name="idleConnectionTestPeriod" value="120" /> <property name="initialPoolSize" value="3" /> <property name="minPoolSize" value="3" /> <property name="maxPoolSize" value="15" /> <property name="numHelperThreads" value="3" /> <property name="preferredTestQuery" value="select 1" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <!-- <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> --> <!-- <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.use_outer_join">true</prop> <prop key="hibernate.jdbc.fetch_size">30</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="hibernate.jdbc.batch_versioned_data">true</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com.djbh.model</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 启动对@AspectJ注解的支持 --> <aop:aspectj-autoproxy/> </beans> ``` springmvc-servlet.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <mvc:annotation-driven/> <mvc:resources location="/static/" mapping="/static/**"/> <mvc:resources location="/attachment/report_html/" mapping="/attachment/report_html/**"/> <context:component-scan base-package="com.djbh.controller" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property> <property name="prefix"><value>/WEB-INF/page/</value></property> <property name="suffix"><value>.jsp</value></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" /> <property name="useCodeAsDefaultMessage" value="true" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--<property name="maxUploadSize" value="10485760"></property> --> </bean> <aop:aspectj-autoproxy proxy-target-class="true" /> </beans> ``` web.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <display-name>djbh</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext*.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>core.web.SystemInitListener</listener-class> </listener> <filter> <filter-name>loginFilter</filter-name> <filter-class>core.web.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>characterEncoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> ```

mybatis dao层空指针异常。

严重: Servlet.service() for servlet [springmvc] in context with path [/fourth] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at com.ssm.fourth.service.MapServiceImpl.selectAll(MapServiceImpl.java:20) at com.ssm.fourth.controller.MapController.second(MapController.java:23) 下面是具体配置 和代码 跪求解决方法 谢谢了 web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> applicationContext.xml <context:component-scan base-package="com.ssm.fourth.service,com.ssm.fourth.dao"></context:component-scan> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <!-- 初始化连接池大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池的最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池的最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池的最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 连接池的最大等待时间 --> <!-- <property name="maxWaite" value="${maxWaite}"></property> --> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybaties/SqlMapConfig.xml"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> springmvc.xml <mvc:annotation-driven/> <context:component-scan base-package="com.ssm.fourth.controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsps/"/> <property name="suffix" value=".jsp"/> </bean> 代码: package com.ssm.fourth.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.ssm.fourth.entity.Map; import com.ssm.fourth.service.MapService; @Controller @RequestMapping(value="b") public class MapController { @Autowired private MapService mapService; @RequestMapping(value="second.action") public String second(){ System.out.println("second"); List<Map> list = mapService.selectAll(); for(int i=0;i < list.size();i++){ System.out.println(list.get(i).getLatitude()); } return "second"; } } package com.ssm.fourth.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.ssm.fourth.entity.Map; @Repository public interface MapDao { public List<Map> selectAll(); } package com.ssm.fourth.service; import java.util.List; import com.ssm.fourth.entity.Map; public interface MapService { public List<Map> selectAll(); } package com.ssm.fourth.service; import java.util.List; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.ssm.fourth.dao.MapDao; import com.ssm.fourth.entity.Map; @Service public class MapServiceImpl implements MapService{ @Qualifier("mapDao") private MapDao mapDao; @Override public List<Map> selectAll() { return this.mapDao.selectAll(); } }

测试时候调用dao层方法报错

Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/Object;Ljava/lang/Throwable;)V at com.alibaba.druid.support.logging.SLF4JImpl.info(SLF4JImpl.java:72) at com.alibaba.druid.pool.DruidDataSource.init(DruidDataSource.java:928) at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1227) at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1223) at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:90) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) at org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:82) at org.mybatis.spring.transaction.SpringManagedTransaction.getConnection(SpringManagedTransaction.java:68) at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:338) at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:84) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:326) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77) 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:433) at com.sun.proxy.$Proxy12.selectOne(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:166) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:83) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59) at com.sun.proxy.$Proxy15.selectByPrimaryKey(Unknown Source) at cn.kgc.jguo.test.Test.main(Test.java:16)

spring定时器,怎么注入dao层?

用的spring3.0 注解配置的定时器,基本功能(定时访问)能实现,现在想定时访问数据库,该怎么注入dao层呢??

利用注解注入service,会空指针异常。而用getBean方式则可以获取到service

在整合springmvc和mybatis时,在controller中注入service,无法注入,具体代码如下 @Controller public class ItemsController { @Autowired private ItemsService itemsService; @RequestMapping("/queryItems") public ModelAndView queryItems(){ if (itemsService == null) System.out.println("DDDDDDDDDDDDDDDDDD"); List<ItemsCustom> itemsList = itemsService.findItemsList(null); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("itemsList", itemsList); modelAndView.setViewName("items/itemsList"); return modelAndView; } } public interface ItemsService { public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo); } public class ItemsServiceImpl implements ItemsService { @Autowired private ItemsMapperCustom itemsMapperCustom; @Override public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo){ return itemsMapperCustom.findItemsList(itemsQueryVo); } } spring的配置,已经在这里非注解的配置了service的bean <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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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 "> <!-- DAO部分 --> <context:property-placeholder location="classpath:db.properties" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="30" /> <property name="maxIdle" value="5" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="ssm.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- service部分 --> <bean id="itemsService" class="ssm.service.impl.ItemsServiceImpl" /> <!-- <context:component-scan base-package="ssm.service.impl"></context:component-scan> <context:annotation-config /> --> <!-- 事务部分 --> <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="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* ssm.service.impl.*.*(..))" /> </aop:config> </beans>

ssm 整合 service层使用Autowired注入dao 报红,可以使用,为什么?

![图片说明](https://img-ask.csdn.net/upload/201712/11/1512966681_57369.png) ### applicationContext.xml 配置 ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 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"> <!-- 读取数据库配置文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 启动上下文的注解配置 --> <context:annotation-config/> <!-- 扫描含有注解的包 --> <context:component-scan base-package="niit.dxs.lehuSSM.service"/> <!-- 配置数据源,使用阿里巴巴的druid数据库连接池 --> <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="initialSize" value="20"/> <!--连接池最大使用连接数量--> <property name="maxActive" value="20"/> <!--连接池最小空闲--> <property name="minIdle" value="0"/> <!--配置获取连接等待超时的时间--> <property name="maxWait" value="60000"/> <!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒--> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!--配置一个连接在池中最小生存的时间,单位是毫秒--> <property name="minEvictableIdleTimeMillis" value="300000"/> <!--连接空闲时测试是否有效--> <property name="testWhileIdle" value="false"/> <!--获取连接时测试是否有效--> <property name="testOnBorrow" value="false"/> <!--归还连接时是否测试有效--> <property name="testOnReturn" value="false"/> <!--打开PSCache缓存,并且指定每个连接上PSCache的大小--> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> </bean> <!-- 配置 mybatis 的SessionFactory 实例 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 指定映射文件位置 --> <property name="mapperLocations" value="classpath*:/niit/dxs/lehuSSM/mapper/*.xml"/> <!-- 指定别名 --> <property name="typeAliasesPackage" value="niit.dxs.lehuSSM.domain"/> </bean> <!--配置DAO接口所在的包--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="niit.dxs.lehuSSM.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--配置一个事务管理器的bean --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> <!--配置声明式事务,在使用处加注解@Transactional--> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <!--用于文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxUploadSize="5242880"/> </beans> ``` ### spring_mvc-servlet.xml 配置 ```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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--启动MVC注解--> <mvc:annotation-driven/> <!--扫描含有注解的包,(控制器所在的包)--> <context:component-scan base-package="niit.dxs.lehuSSM.controller"/> <!--配置视图解析器,指定视图所在路径,视图文件后缀名--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/" p:suffix=".jsp"/> <!--保证静态资源不被拦截--> <mvc:default-servlet-handler/> <!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <!-- 表示拦截所有 --> <mvc:mapping path="/**"/> <!--<mvc:exclude-mapping path="/css/*.css"/>--> <!-- 指定拦截器 --> <bean class="niit.dxs.lehuSSM.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> </beans> ``` ### web.xml 配置 ```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 xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>lehuSSM</display-name> <!--默认启动页--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml,classpath:spring_mvc-servlet.xml</param-value> </context-param> <!-- 过滤器统一编码 --> <filter> <filter-name>Spring character encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param><!-- 过滤请求字符集 --> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param><!-- 过滤响应字符集 --> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>Spring character encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring容器配置 ,当服务器启动,加载web.xml配置文件--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 控制器 当服务器启动,加载spring_mvc-servlet.xml配置文件--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring_mvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- mvc控制器映射 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ```

无效的bean定义与类路径中定义的名字“数据源”资源[spring-mybatis]

org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in class path resource [spring-mybatis.xml]: Could not resolve placeholder 'driver' in string value "${driver}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'driver' in string value "${driver}" at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:211) at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:223) at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:86) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:162) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'driver' in string value "${driver}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer$PlaceholderResolvingStringValueResolver.resolveStringValue(PropertyPlaceholderConfigurer.java:259) at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282) at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveValue(BeanDefinitionVisitor.java:204) at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitPropertyValues(BeanDefinitionVisitor.java:141) at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:82) at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:208) ... 18 more 报错信息 这个是哪里错了 要怎么解决

MyBatis 传参错误……

我想要在JSP中通过两个date传参到action,然后想通过两个日期查询出表里的内容,但是参数传递到serviceImp的时候就卡住了……还是个小白所以很多不懂的(╥╯^╰╥)……相关代码全部贴出来了……希望大大们能解答一下…… 我个人感觉可能是mapper里面没有对两个参数进行注解,但是我不懂怎么改…… 先贴出报错…… 严重: Servlet.service() for servlet [springmvc] in context with path [/MedicalExaminationSystem] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'payDate' not found. Available parameters are [0, 1, param1, param2]] with root cause org.apache.ibatis.binding.BindingException:** Parameter 'payDate' not found. Available parameters are [0, 1, param1, param2]** at org.apache.ibatis.binding.MapperMethod$ParamMap.get(MapperMethod.java:165) ache.ibatis.reflection.wrapper.MapWrapper.get(MapWrapper.java:44) //action类 @Controller public class ReportAction { @Autowired IReportService Service; @RequestMapping("/getPayM") // 通过两个日期查询两个日期内的金额 public ModelAndView GetPayMoney(Date date1, Date date2) { ModelAndView modelAndView = new ModelAndView("Report"); System.out.println("开始日期=" + date1); System.out.println("结束日期=" + date2); TPayMoney list = Service.querySumMoney(date1, date2); System.out.println("跳转信息发送到界面" + list); if (list != null) {// 判断不为空跳转 System.out.println("返回"); modelAndView.addObject(list); return modelAndView; } else { return modelAndView; } } } //service接口 public interface IReportService { public TPayMoney querySumMoney(Date date1,Date date2); } //servic实现类 @Service public class ReportServiceImp implements IReportService{ @Autowired private TPayMoneyMapper payMoneyMapper; @Override public TPayMoney querySumMoney(Date date1, Date date2) { System.out.println("ipm date1"+date1); System.out.println("ipm date2"+date2);//还可以读取到 TPayMoney list = payMoneyMapper.selectByDate(date1, date2); System.out.println("出的来么"+list);//这里就读不出来了 if (list != null) { return list; } return null; } } //bean类 public class TPayMoney { private BigDecimal payId; private BigDecimal batId; private BigDecimal payAccount; private BigDecimal payPays; private String payState; private Date payDate; public BigDecimal getPayId() { return payId; } public void setPayId(BigDecimal payId) { this.payId = payId; } public BigDecimal getBatId() { return batId; } public void setBatId(BigDecimal batId) { this.batId = batId; } public BigDecimal getPayAccount() { return payAccount; } public void setPayAccount(BigDecimal payAccount) { this.payAccount = payAccount; } public BigDecimal getPayPays() { return payPays; } public void setPayPays(BigDecimal payPays) { this.payPays = payPays; } public String getPayState() { return payState; } public void setPayState(String payState) { this.payState = payState == null ? null : payState.trim(); } public Date getPayDate() { return payDate; } public void setPayDate(Date payDate) { this.payDate = payDate; } } //mapper @Repository public interface TPayMoneyMapper { //用时间查询内容 TPayMoney selectByDate(Date date1,Date date2); } //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.great.dao.TPayMoneyMapper"> <resultMap id="BaseResultMap" type="com.great.entity.TPayMoney"> <!-- WARNING - @mbg.generated This element is automatically generated by MyBatis Generator, do not modify. This element was generated on Tue Sep 26 14:09:25 CST 2017. --> <id column="PAY_ID" jdbcType="DECIMAL" property="payId" /> <result column="BAT_ID" jdbcType="DECIMAL" property="batId" /> <result column="PAY_ACCOUNT" jdbcType="DECIMAL" property="payAccount" /> <result column="PAY_PAYS" jdbcType="DECIMAL" property="payPays" /> <result column="PAY_STATE" jdbcType="VARCHAR" property="payState" /> <result column="PAY_DATE" jdbcType="DATE" property="payDate" /> </resultMap> <sql id="Base_Column_List"> <!-- 查询两个日期之间的数据 --> <select id="selectByDate" parameterType="com.great.entity.TPayMoney" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from TBL_PAYMONEY where to_char(TBL_PAYMONEY.pay_date,'yyyy-mm-dd') between '#{payDate}' and '#{payDate}'; </select> </mapper> 最后一个数据库 /*==============================================================*/ /* Table: tbl_paymoney 付款表 */ /*==============================================================*/ create table tbl_paymoney ( pay_id NUMBER(20) not null, bat_id NUMBER(20), pay_account NUMBER(10,2), pay_pays NUMBER(10,2), pay_state VARCHAR2(20), pay_date DATE, constraint PK_TBL_PAYMONEY primary key (pay_id) ); comment on table tbl_paymoney is '付款表'; comment on column tbl_paymoney.pay_id is '付款ID'; comment on column tbl_paymoney.bat_id is '批次ID'; comment on column tbl_paymoney.pay_account is '赊账'; comment on column tbl_paymoney.pay_pays is '已付款金额'; comment on column tbl_paymoney.pay_state is '状态'; comment on column tbl_paymoney.pay_date is '日期';

spring的aop在dao层能得到所调用的sql吗?

想在dao层做切面来记录修改的操作,但是希望记录执行前的数据,因此需要知道执行的语句,用aop有办法得到这个sql吗,另外能知道更新的是哪个对象吗?用mybatis做orm的。

spring4.0+mybatis3.3+tomcat8.0整合出的NoClassDefFoundError一个问题

具体工程见如下地址: https://yunpan.cn/cr5AZCTwuI7pp 访问密码 e565 代码是我学习的demo,第一次做spring+mybatis的开发。 本来所有代码放在一个工程(参见附件的springMVC03_single.rar)运行都是ok的。 但是我把dao和pojo两块代码单独出一个工程后(参见附件的springMVC03_mutiproj.rar),加载就出现问题了。 加载的错误是: ![图片说明](https://img-ask.csdn.net/upload/201601/29/1454075373_508953.png) 错误调用栈信息如下: ![图片说明](https://img-ask.csdn.net/upload/201601/29/1454075359_525757.png) 初步怀疑和tomcat的webapp类加载器有关,具体tomcat的加载器原理到底是怎么样,为何会引起这个问题以及如何规避这个问题请各位大侠赐教

SSM中Controller自动注入service失败

Root Cause org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'loginServiceImpl'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ssm.service.LoginServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:364) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1269) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:171) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) ## 在Controller中自动注入service就报以上错误 ![图片说明](https://img-ask.csdn.net/upload/202004/13/1586763996_66970.jpg) ## 该service为 ![图片说明](https://img-ask.csdn.net/upload/202004/13/1586764249_143874.jpg) spring-dao.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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"> <!--读取properties文件 --> <context:property-placeholder location="classpath:db.properties" /> <context:annotation-config></context:annotation-config> <!--配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${driver}</value> </property> <property name="url"> <value>${url}</value> </property> <property name="username"> <value>${username}</value> </property> <property name="password"> <value>${password}</value> </property> </bean> <!-- 配置sqlsessionFactory --> <!-- 查看源码便可知注入的property的名字 --> <!-- 可以读取mybatis-config.xml文件,也可以不读取,信息全都在配置在spring中 --> <!-- <property name="configLocation" value="classpath:mybatis-config.xml" /> --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.ssm.bean"></property> <property name="configurationProperties"> <props> <prop key="cacheEnabled">true</prop> <prop key="lazyLoadingEnabled">false</prop> </props> </property> <!--告诉spring扫描映射文件 --> <property name="mapperLocations" value="classpath:com/ssm/dao/mapper/*.xml"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.dao.mapperInterface"></property> </bean> </beans> ``` ## 以下是spring-service.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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" 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"> <!-- 扫描添加了spring注解的类 --> <context:component-scan base-package="com.ssm.service.*" /> <!-- 采用注解方式配置 --> <context:annotation-config /> <!-- 配置事务管理器 --> <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="get*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="select*" propagation="REQUIRED" rollback-for="Exception" /> </tx:attributes> </tx:advice> <!-- spring的aop配置 --> <aop:config proxy-target-class="true"> <aop:pointcut id="txPointcut" expression="execution(* com.ssm.service..*.*(..)) " /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> </beans> ``` ## 以下spring-web.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: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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 配置SpringMVC --> <!-- 1.开启SpringMVC注解模式 --> <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 --> <mvc:annotation-driven /> <!-- 采用注解方式配置 --> <context:annotation-config /> <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 --> <!-- <mvc:resources mapping="/images/**" location="/images/"/> <mvc:resources mapping="/js/**" location="/js/"/> <mvc:resources mapping="/css/**" location="/css/"/> <mvc:resources mapping="/fonts/**" location="/fonts/"/> <mvc:resources mapping="/script/**" location="/script/"/> --> <mvc:default-servlet-handler/> <!-- 3.配置jsp 显示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 4.扫描web相关的bean --> <context:component-scan base-package="com.ssm.web.controller" /> </beans> ``` ##最后是web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>SSMDemo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 配置spring读取的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-dao.xml classpath:spring-service.xml </param-value> </context-param> <!--配置监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 如果是用mvn命令生成的xml,需要修改servlet版本为3.1 --> <!-- 配置DispatcherServlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springMVC需要加载的配置文件 spring-dao.xml,spring-service.xml,spring-web.xml Mybatis - > spring -> springmvc --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-web.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置编码过滤 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/</url-pattern> </filter-mapping> </web-app> ``` ##求解决!!

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>

数据可视化开发(springmvc+echarts)

用SpringMVC+Echarts模式开发,请有经验的介绍一下,能有个案例的话,不胜感激,谢谢,前端用JSP照片,想在dao层实例化option方式呈现,ajax后台调用js实现已经初步完成,还有就是希望有好的可视化建议,望提出,谢谢,

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

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

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

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

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

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

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

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

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

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

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

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

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

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

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

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

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

优雅的替换if-else语句

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

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

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

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

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

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

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

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中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多个条件是什么逻辑关系?条件判断在什么时候执...

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

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

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

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

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

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

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

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

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

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

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

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

一文带你入门Java Stream流,太强了

两个星期以前,就有读者强烈要求我写一篇 Java Stream 流的文章,我说市面上不是已经有很多了吗,结果你猜他怎么说:“就想看你写的啊!”你看你看,多么苍白的喜欢啊。那就“勉为其难”写一篇吧,嘻嘻。 单从“Stream”这个单词上来看,它似乎和 java.io 包下的 InputStream 和 OutputStream 有些关系。实际上呢,没毛关系。Java 8 新增的 Stream 是为...

立即提问
相关内容推荐