作成した Spring プロファイルで JUnit テストを実行しようとすると問題が発生します。実際には、オートワイヤーできないリポジトリ Bean を除いて、プロファイルは正常に機能します。
これは、spring-integration-context.xml で永続性を構成するために使用するコードのフラグメントです。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
.... Some namespaces definitions
<beans profile="dev">
<jdbc:embedded-database id="dataSource" type="H2" />
<!-- Define the JPA transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="vendorAdaptor" />
<property name="packagesToScan" value="guiatv.persistence.*" />
</bean>
<bean id="abstractVendorAdaptor" abstract="true">
<property name="generateDdl" value="true" />
<property name="database" value="H2" />
<property name="showSql" value="false" />
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="vendorAdaptor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
parent="abstractVendorAdaptor">
</bean>
</beans>
... Some other beans, some of them with the same "dev" profile
</beans>
したがって、永続化構成全体を「Beans profile」要素でラップするだけで十分だと思いました。
さて、私のJUnitテストクラスから:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationTest.class)
@ActiveProfiles("dev")
public class ScheduleLoaderTests {
@Autowired
ScheduleLoader schedLoader;
@Autowired
ScheduleRepository shedRep;
@Test
public void someTest() { ... }
}
そして、 ApplicationTest クラスに次の注釈を付けています。
@ImportResource("classpath:/META-INF/spring/integration/spring-integration-context.xml")
しかし、テストを実行すると、次の例外が発生します。
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [guiatv.persistence.repository.ScheduleRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
私のテストクラスでは、ScheduleLoader は以前に自動配線されていることに注意してください。実際、その Bean は開発プロファイル内にもあります。@ActiveProfiles("dev")アノテーションなしでテストを実行しようとすると 、予想どおり、 ScheduleLoader failed autowiringによって例外がスローされます(dev プロファイルにのみあるため)。
では、Spring プロファイルと永続化構成の問題は何ですか?
PD: リポジトリとエンティティ クラスがその中にあることを確認しました
guiatv.persistence.*
パッケージ。
ちなみに、私はSpring Bootを使っているので、@ActiveProfiles("dev") アノテーションを書く代わりに、application.propertiesファイルに spring.profiles.active=devを追加して動作させることも試みました。
アップデート
また、すべての「Beans プロファイル」要素を削除して、すべてのコンポーネントがルート「Beans」要素の子になるようにすると、@ActiveProfiles("dev") アノテーションなしまたは @ActiveProfiles( 「デフォルト」) 注釈。