概要
我正在构建一个spring-mvc Web应用程序并尝试使用Mybatis和DAO进行数据访问。
我成功配置了Mybatis,并且能够从Mysql服务器获取预期的数据。
但是当我尝试将DAO与Mybatis一起使用时出现问题。
错误
如下所示,它是NullPointerException
。
INFO : com.*****.web.controller.ExampleController - testDaoSelect action has been executed. No parameter has been taken.
INFO : com.*****.web.service.exampleService - Executed or not??
09, March, 2015 5:07:28 PM org.apache.catalina.core.StandardWrapperValve invoke
Fatal: Servlet.service() for servlet [appServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.*****.web.service.exampleService.sampleList(exampleService.java:29)
at com.*****.web.controller.ExampleController.testDaoSelect(ExampleController.java:188)
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:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
复制ERORR
从AJAX调用开始。
$('#DaoSelectTest').click(function(e) {
$.ajax({
type: "POST",
url: "/testDaoSelect.fst",
data: {},
success: function (result) {
console.log(result);
var html = "Querying was successful. Check out console logs. <br/>";
html += "Done with the test. <a href='/daoSample.fst'>Click here</a> ";
html += "And proceed to the next.";
$('#sampleTable').html(html);
},
error: function (result) {
// error...
}
});
});
然后,执行动作..
@Controller
public class ExampleController {
// Mybatis direct
@Autowired
private SqlSession sqlSession;
// Dao
@Autowired
private exampleService exService;
.
.
.
.
.
@RequestMapping("/testDaoSelect")
@ResponseBody
public List<HashMap<String, Object>> testDaoSelect(HttpServletRequest request, HttpServletResponse response) {
logger.info("testDaoSelect action has been executed. No parameter has been taken.");
List<HashMap<String, Object>> result = exService.sampleList();
logger.info("result size is... " + result.size());
return result;
}
调用textDaoSelect
没问题,接下来是服务类。
@Service
@Transactional
public class exampleService {
private Log logger = LogFactory.getLog(this.getClass());
@Autowired
private exampleDao exDao;
@Transactional(readOnly = true)
public List<HashMap<String, Object>> sampleList() {
logger.info("Executed or not??");
return exDao.sampleList();
}
}
BOOM〜!此处
exDao在这里为空,此处出现NullPointException
。它没有正确连线。为什么??我该怎么办?
我的exampleDao
public interface exampleDao {
public List<HashMap<String, Object>> sampleList();
}
**我的exampleDaoImplement
public class exampleDaoImplement extends SqlSessionDaoSupport implements exampleDao {
private static final Logger logger = LoggerFactory.getLogger(exampleDaoImplement.class);
public List<HashMap<String, Object>> sampleList() {
// TODO Auto-generated method stub
logger.info("I've reached impl class....");
return getSqlSession().selectList("Example.selectTest");
}
}
MY ROOT CONTEXT
(忘掉******
了......)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://*******:3306/*****_web"/>
<property name="username" value="root"/>
<property name="password" value="*******"/>
</bean>
<bean id ="sqlSessionFactory" class= "org.mybatis.spring.SqlSessionFactoryBean" >
<property name ="dataSource" ref= "dataSource"></property >
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
</bean >
<bean id ="transactionManager"
class= "org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name ="dataSource" ref= "dataSource"></property >
</bean >
<bean id ="sqlSession"
class= "org.mybatis.spring.SqlSessionTemplate" >
<constructor-arg ref= "sqlSessionFactory"></constructor-arg >
</bean >
<bean id ="exService" class= "com.*****.web.service.exampleService" ></bean >
</beans>
我的servlet-context
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.******.web.controller" />
</beans:beans>
我已经用Google搜索了半天,并得到了一些提示,但没有确切的解决方案。似乎是什么事情?
ADDED
谷歌搜索时,我得到了这个提示并进行了相应的配置。
<bean id ="exDao" class= "com.*****.web.dao.implement.exampleDaoImplement" >
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean >
(没有定义属性,它在启动服务器时抛出错误,说需要属性sqlSessionFactory
或SqlSessionTemplate
。)
但它不起作用......即使使用此配置,仍然存在nullpoint错误。
答案 0 :(得分:3)
第一个想法:在 servlet-context.xml 中,您写道:
<context:component-scan base-package="com.******.web.controller" />
这意味着Spring会在此文件夹中查找带注释的类(如@Service
和其他) 。你有没有机会把你的DAO放在&#34; com。****** .web.controller&#34;夹?这可以解释为什么它仍然是null
。
一个简单的测试是使用&#34; com。******&#34;确保扫描每个文件夹。
第二个想法:如果你希望Spring实现你的DAO类,你必须在DAO接口的具体实现中添加@Repository
注释。
第三个想法:您不应该对同一个类使用XML配置和注释。在您的示例中,如果您在 exampleService 类中使用<bean id ="exService" class= "com.*****.web.service.exampleService"></bean >
并且@Service
涵盖服务的目录,则不需要使用<component-scan>
是
最后的注释:您在评论中写道,使用@Service("exService")
解决了您的问题。这是因为,如果您没有指定组件的名称,Spring会查找具有给定类型的任何现有bean(而不是其名称)。因此,它注入了您在XML中声明的bean,它具有null
DAO。
为了避免这种问题,你应该总是在你使用它的变量的名称之后明确地命名你的bean,这里@Service("exService")
切换&#34;按名称绑定&#34;行为,使您的代码按预期工作:
// This works because the name of the variable
// matches the @Service("exService") annotation
@Autowired
private ExampleService exService;
感谢@RohitJain的最后一句话。
与您的问题无关,Java类和接口应始终用大写字母书写(例如&#34; ExampleDao&#34;,&#34; ExampleDaoImplement&#34;&#34; ExampleService&#34;)。
答案 1 :(得分:0)
这是一个非常疯狂的猜测,但我认为您应该使用重构重命名将exampleDaoImplement
重命名为exampleDaoImpl
。
答案 2 :(得分:0)
我的实现使用纯XML spring配置,一切都很好,因为web-app能够正常启动而没有任何错误。
但是对于通过名称自动装配的DAO实例,我仍然有空例外,我通过添加一个getter和一个setter来解决它。