Intellij项目的目录:

src/main/java/rewards/testdb/schema.sql
src/main/java/rewards/testdb/test-data.sql
src/main/java/rewards/testdb/config/alternate-datasource-config.xml
src/main/java/rewards/testdb/config/AlternateDataSourceConfigTests.java


受测试的Bean配置(来自alter-datasource-config.xml):

<bean id="dataSource-createdFromList" class="org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean" lazy-init="true">
    <property name="databaseName" value="rewards" />
    <property name="databasePopulator">
        <bean class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
            <property name="scripts">
                <util:list>
                    <value>classpath:rewards/testdb/schema.sql</value>
                    <value>classpath:rewards/testdb/test-data.sql</value>
                </util:list>
            </property>
        </bean>
    </property>
</bean>


我在单元测试中遇到错误:

Caused by: java.io.FileNotFoundException: class path resource [rewards/testdb/schema.sql] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)


但是,如果我将目录修改为:

src/main/java/rewards/testdb/config/schema.sql
src/main/java/rewards/testdb/config/test-data.sql
src/main/java/rewards/testdb/config/alternate-datasource-config.xml
src/main/java/rewards/testdb/config/AlternateDataSourceConfigTests.java


并修改我的bean配置:

<bean id="dataSource-createdFromList" class="org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean" lazy-init="true">
        <property name="databaseName" value="rewards" />
        <property name="databasePopulator">
            <bean class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
                <property name="scripts">
                    <util:list>
                        <value>classpath:rewards/testdb/config/schema.sql</value>
                        <value>classpath:rewards/testdb/config/test-data.sql</value>
                    </util:list>
                </property>
            </bean>
        </property>
    </bean>


...我的测试通过了。

为什么?

最佳答案

在您的Idea项目配置中,将目标路径指向项目目标文件夹:Edit Configurations-> Deployment-> Edit Artifact(单击铅笔图标)->将“ Output Directory”输入设置为“ your_project_folder_path / target”
然后,无论何时编辑jdbc.properties文件,此操作都将在重新启动后生效。

这对Maven Web项目有效。

10-07 16:30
查看更多