SpringMVC+Hibernate用junit测试的时候报空指针错误,请各位帮下小弟啦

heyimateyang 2016-12-26 10:06:51
先上代码:
spring.xml的配置

<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 扫描service自动注入为bean -->
<context:component-scan base-package="org.heyimateyang.*"/>



spring-mvc.xml 配置

<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

<!-- 自动扫描@Controller注入为bean -->
<context:component-scan base-package="org.heyimateyang.controller" />

<!-- 以下为SpringMVC配置 -->
<mvc:annotation-driven>
<!-- 返回json数据,@response使用 -->
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>

</bean>
</mvc:message-converters>
</mvc:annotation-driven>

<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views" />
<property name="suffix" value=".jsp" />
</bean>

</beans>


我是刚学习MVC的配置,这个错误看了2天都没解决,希望有大神可以帮帮忙啦,不胜感激
...全文
189 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
小灯光环 2016-12-27
  • 打赏
  • 举报
回复
好像少一个注解,加上试试看:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml",
"classpath:spring-hibernate.xml" })
star19860411 2016-12-27
  • 打赏
  • 举报
回复
按照命名规范走,都统一起来
ArthurKingYs 2016-12-27
  • 打赏
  • 举报
回复
看一下 @Autowired 和相关注入方式问题是否成功,xml文件相关内容是否书写
青元子 2016-12-27
  • 打赏
  • 举报
回复
直接参考我的博客吧
  • 打赏
  • 举报
回复
@Autowired private userService userService; 注意一下命名规范,首字母换成大写试试
zwbonline1112 2016-12-27
  • 打赏
  • 举报
回复
你的配置文件是放在类路径下面吗?还有就是测试类要加上@RunWith(SpringJUnit4ClassRunner.class)
heyimateyang 2016-12-27
  • 打赏
  • 举报
回复
真的谢谢各位的帮助,问题已经解决了..不胜感激各位
heyimateyang 2016-12-26
  • 打赏
  • 举报
回复
Test的代码:

package org.heyimateyang.test;

import java.util.UUID;

import org.heyimateyang.model.User;
import org.heyimateyang.service.userService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;




@ContextConfiguration(locations = { "classpath:spring.xml",  
        "classpath:spring-hibernate.xml" }) 
public class Test {
	
	@Autowired  
    private userService userService;
	
	@org.junit.Test  
    public void saveTest() {  
        User acctUser = new User();  
       
        acctUser.setName("andy");   
        acctUser.setPassword("123");  
        userService.saveUser(acctUser);
    }  

}

测试出来结果是这样:

java.lang.NullPointerException
	at org.heyimateyang.test.Test.saveTest(Test.java:28)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)


heyimateyang 2016-12-26
  • 打赏
  • 举报
回复
UserDaoImpl代码:

package org.heyimateyang.dao.impl;

import org.heyimateyang.dao.UserDao;
import org.heyimateyang.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


@Repository("userDao")
public class UserDaoImpl implements UserDao{
	
	@Autowired  
    private SessionFactory sessionFactory;  
  
    private Session getCurrentSession() {  
        return this.sessionFactory.getCurrentSession();  
    }  

    public void saveUser(User user) {
       this.getCurrentSession().save(user);
    }
	

}

userSerciveImpl代码:

package org.heyimateyang.service.impl;

import org.heyimateyang.dao.UserDao;
import org.heyimateyang.model.User;
import org.heyimateyang.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("userService")
public class userServiceImpl implements userService {
	
	@Autowired
	private UserDao userDao;

	public void saveUser(User user) {
		
		this.userDao.saveUser(user);
	}

}

heyimateyang 2016-12-26
  • 打赏
  • 举报
回复
spring-hibernate.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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
        http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">   
                        
                        
 	<!-- 配置数据源 c3p0 -->  
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
        destroy-method="close">  
        <property name="driverClass" value="${jdbc.driver}" />  
        <property name="jdbcUrl" value="${jdbc.url}" />  
        <property name="user" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  
  
        <!-- 请求超时时间 -->  
        <property name="checkoutTimeout" value="30000" />  
        <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->  
        <property name="idleConnectionTestPeriod" value="30" />  
        <!-- 连接数据库连接池最大空闲时间 -->  
        <property name="maxIdleTime" value="30" />  
        <!-- 连接池初始化连接数 -->  
        <property name="initialPoolSize" value="5" />  
        <property name="minPoolSize" value="5" />  
        <property name="maxPoolSize" value="20" />  
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->  
        <property name="acquireIncrement" value="5" />  
    </bean>  
    
    <!-- 配置hibernate的SessionFactory -->  
    <bean id="sessionFactory"  
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
        <!-- 注入数据源 相关信息看源码 -->  
        <property name="dataSource" ref="dataSource" />  
        <!-- hibernate配置信息 -->  
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>  
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
  
                <!-- 开启二级缓存 ehcache -->  
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>  
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>  
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>  
                <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}  
                </prop>  
            </props>  
        </property>  
        <!-- 扫描hibernate注解配置的entity -->  
        <property name="packagesToScan" value="org.heyimateyang.model" />  
    </bean>  
  
    <!-- 配置事务管理器 -->  
    <bean id="transactionManager"  
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>
    
   <!-- 配置事务增强处理Bean,指定事务管理器 -->  
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">  
        <!-- 配置详细事务处理语义 -->  
        <tx:attributes>  
            <tx:method name="insert*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
  
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="save*" propagation="SUPPORTS" read-only="true" />  
  
            <!-- 其他采用默认事务方式 -->  
            <tx:method name="*" />  
  
        </tx:attributes>  
    </tx:advice>  
  
    <!-- Spring aop事务管理 -->  
    <aop:config>  
        <!-- 配置切入点 -->  
        <aop:pointcut id="transactionPointcut"  
            expression="execution(* org.heyimateyang.service..*impl.*(..))" />  
        <!-- 指定在txAdvice切入点应用txAdvice事务增强处理 -->  
        <aop:advisor pointcut-ref="transactionPointcut"  
            advice-ref="transactionAdvice" />  
    </aop:config>  
         
</beans>

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧