Spring和MyBatis整合,Controller利用注解获取Service对象是Null

JoruaChan
  • 138

最近在学习整合Spring+MyBatis,最简单的配置,报这个错误:

Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

1.applicationContext.xml:


    <!-- 数据源配置, 使用Tomcat JDBC连接池 -->
   <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
       <property name="url" value="jdbc:mysql://localhost:3306/jsp_db"/>
       <property name="name" value="root"/>
       <property name="password" value=""/>
    <property name="defaultAutoCommit" value="false" />
   </bean> 
   
<!-- 配置mybatis的配置文件位置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- Mapper文件位置 -->
    <property name="mapperLocations" value="/WEB-INF/config/mybatis/*Mapper.xml"/>
    <!-- mybatis配置文件位置 -->
    <property name="configLocation" value="/WEB-INF/config/mybatis/config.xml"/>
</bean>

<!--MapperScannerConfigurer自动扫描将Mapper接口生成代理注入到Spring  -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 映射器接口文件的包路径, -->
    <property name="basePackage" value="com.jackchan.dao" />
</bean>


   

2.Springmvc配置

<beans xmlns="http://www.springframework.org/schema/beans"   
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:p="http://www.springframework.org/schema/p"  
    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-3.0.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">
    
    <!-- 加载包中的controller  注解扫描包 -->  
       <context:component-scan base-package="com.jackchan.controller"/> 
    
</beans>

3.MyBatis配置文件

<configuration>
    <settings>
        <setting name="cacheEnabled" value="true" />
    </settings>    
</configuration>

4.Mapper文件

<mapper namespace="com.jackchan.dao.IPTableDao">
    
    <select id="selectAll" resultType="com.jackchan.entity.IPTable">
        select * from table_ip
    </select>
    
    <select id="selectByCountry" parameterType="String" resultType="com.jackchan.entity.IPTable">
        select * from table_ip where country=${country}
    </select>
    
    <select id="selectByISP" parameterType="String" resultType="com.jackchan.entity.IPTable">
        select * from table_ip where isp=${isp}
    </select>
    
</mapper>

5.DAO

@Repository
public interface IPTableDao {
    
    List<IPTable> selectAllIP();
    
    List<IPTable> selectByCountry(String country);
    
    List<IPTable> selectByISP(String isp);
    
}

6.Service层

@Service
public class IPService {
    
    @Resource 
    IPTableDao tableDao;
    
    public String getIPData(String param) {
        
        List<IPTable> tables = null;
        
        if (param == "all") {
            tables = tableDao.selectAllIP();
        }else if (param == "country") {
            tables = tableDao.selectByCountry(param);
        }else {
            tables = tableDao.selectByISP(param);
        }
        
        StringBuffer sBuffer = new StringBuffer();
        
        for (IPTable tableIp : tables) {
            sBuffer.append(tableIp.getIp()).append(":").append(tableIp.getPort()).append(",")
                .append(tableIp.getCountry()).append(",").append(tableIp.getIsp());
            sBuffer.append("\r\n");
        }
        
        return sBuffer.toString();
    }
    
}

7.Controller层

@Controller()
@RequestMapping(value="/index")
public class IndexController {

    @Resource
    private IPService ipService;
    
    @RequestMapping(value="/hello.html",method=RequestMethod.GET)
    public void index(HttpServletRequest request,HttpServletResponse response) {
        
        System.out.println("haha"+ipService);
        
        String text = ipService.getIPData(request.getParameter("param"));
        
        //ResponseUtil里封装了输出json格式数据方法
        ResponseUtil.renderJson(response, text);
    
    }
    
}

8.抛出的异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'indexController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'ipService' is defined
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:828)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    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)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'ipService' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1174)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:283)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:201)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:201)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:512)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:486)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:615)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
    ... 36 more

9.项目目录结构

clipboard.png

望大家帮帮忙一下!

回复
阅读 5.8k
3 个回答
MaxValue
  • 785
✓ 已被采纳

报错应该不止这一行吧?一般这种报错都是一个带一个,一个带一个的,controller带出了service,service带出了dao,你把报错信息全贴出来看看.
spring的配置文件那个datasource为什么不写在上面呢,遵循从上到下的加载方式啊.


update: 评论不好上图. @jackchan

clipboard.png


update: 评论不好上图. @jackchan
clipboard.png
你把你的base-package后面的值中controller去掉在重启试试.你这仅仅是扫描了controller,并没有扫描servicedao
你把你工程结构截图发一下看看...

没看到有配置包扫描。

lizhaowei213
  • 3
新手上路,请多包涵
宣传栏