nested exception is java.io.FileNotFoundException: class path resource [spring-mybatis.xml] cannot be opened

idea+maven+springmvc项目,做单元测试报错,找不到配置文件。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TestMybatis {
    private static Logger logger = LoggerFactory.getLogger(TestMybatis.class);
    @Resource
    private MessageService messageService=null;
    @Test
    public  void test1(){
        Message message=messageService.getMessageById(1);
        logger.info("Command====:{}", message.getCommand());
    }

}

点击"classpath:spring-mybatis.xml"还能找到文件。

已经配置文件放在src/main/resouces目录下,并且设置成Resources Root。但是不起作用,编译后发现target/classes文件下没有该配置文件。

经过网上一番搜索,解决IDEA的这个问题有两种方式。

第一种是建立src/main/resources文件夹,将xml等资源文件放置到这个目录中。maven工具默认在编译的时候,会将resources文件夹中的资源文件一块打包进classes目录中。

第二种解决方式是配置maven的pom文件配置,在pom文件中找到<build>节点,添加下列代码:

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

显然,第一种在这对我不好使。

我看了下pom.xml,因为是项目学习,在网上copy的。发现已经有了一个resource配置,就是上面贴出来。(因为src/main/java下面有mapper.xml,所以做了配置)。

于是我把<resources>节点删掉,重新编译,发现src/main/resouces下面的配置文件已经到target/classes文件夹下。但是不幸的是,之前的mapper.xml不在classes文件下了。

不过没关系,我们把两种都配置在resources即可。

<build>
    <resources>
         <resource>
            <directory>src/main/java</directory>
            <includes>
                    <include>**/*.xml</include>
             </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
          </resource>
     </resources>
</build>

 

文章来自:https://www.cnblogs.com/xingxing0521/p/9416400.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3