记一次junit 运行错误调试 Failed to load ApplicationContext

任何事物的发展都不是一帆风顺的,我们每个人都会经历曲折与困难,只不过是有的人经历的多,有的人经历的少,或是当我们处于困难挫折时的周围环境有所不同。

项目是之前的老项目了,最近又增加了一个新功能,想着写个方法测试一下新增的代码,但是在使用juint工具进行测试时,一直报Failed to load ApplicationContext这个错误,一开始摸不着头脑,网上各种资料查找,都不能解决自己的问题,满屏的错误日志,一时间心烦意乱。就在自己将要放弃时,还是自己静下心来,翻看错误日志发现:

Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'maxActive'; nested exception is java.lang.NumberFormatException: For input string: "${master.maxActive}"

于是,才明白配置文件内容没有获取到,想到项目里面配置了多环境参数切换,才有了如下的分享。

 

框架:springmvc+mybatis

报错内容为:java.lang.IllegalStateException: Failed to load ApplicationContext

错误原因:项目配置了多环境参数切换,未指定@ActiveProfiles("dev")。导致配置文件内容读取出错。

junit代码如下:

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@ActiveProfiles("dev")
@ContextConfiguration(locations = {"classpath*:spring-mybatis.xml","classpath*:spring-mvc.xml"})
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class OrgReportTaskServiceTest {
    Logger logger = LoggerFactory.getLogger(OrgReportTaskServiceTest.class);
    @Resource
    private OrgReportTaskService orgReportTaskService;
    
    @Test
    public void testDelete() {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        int result = this.orgReportTaskService.deleteByIds(list);
        logger.info("result:"+result);
        
    }
}

mybatis配置文件:

    <!-- Spring和MyBatis完美整合,不需要mybatis的配置映射文件
         **表示可以表示任意多级目录    *表示多个任意字符
     -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-page.xml" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations">
            <array>
                <value>classpath*:com/beetle/**/mapping/*.xml</value>
            </array>
        </property>
    </bean>

注意:mapperLocations内容:classpath后面一定要加上*,否则的话,会报一下异常:

Caused by: org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.beetle.system.mapper.SysConfigMapper.selectByPrimaryKey 

classpath和classpath*区别: 

classpath:只会到你的class路径中查找找文件。

classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章