私の古い XML 構成プロジェクトでは、構成で次のことを行うことができました。
mvc-context.xml
<context:component-scan base-package="com.foo" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<mvc:annotation-driven/>
service-context.xml
<context:spring-configured />
<context:annotation-config />
<context:component-scan base-package="com.foo" >
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
私のテストでは、次のことができます
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy(value = {
@ContextConfiguration(classes = { MockServices.class }),
@ContextConfiguration({ "classpath:/META-INF/spring/mvc-servlet-context.xml" }),
})
public class FooControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = webAppContextSetup(wac).build();
}
}
そして、サービスと JPA リポジトリをロードせずに、MVC 構成に対してテストを実行し、代わりにモック@Autowired
をコントローラーに入れることができました。
ただし、Spring Boot アプリケーションには、メイン コンテキスト構成に次のものがあります。
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
}
これ@ComponentScan
は明らかにすべて、、@Controller
など@Service
を見つけます
MVC コンテキストをテストしようとすると、不要なサービスとリポジトリがロードされます。
私がやろうとしたことは、2つの新しい構成を作成することでした
Mvc.java
@Configuration
@ComponentScan(basePackages = { "com.foo" }, useDefaultFilters = false, includeFilters = {@Filter(value = org.springframework.stereotype.Controller.class)} )
@Order(2)
public class Mvc {
}
Services.java
@Configuration
@ComponentScan(basePackages = { "com.foo" }, useDefaultFilters = false, excludeFilters = {@Filter(value = org.springframework.stereotype.Controller.class)} )
@Order(1)
public class Services {
}
ただし、これは機能しません。アプリを起動しようとすると、@Autowire
エラーが発生しますNo qualifying bean of type
私はこれについて間違った方法で進んでいますか?
JPA EntityManagers、Spring Data Repositories などをロードする時間のペナルティなしで、MVC コンテキストでテストを実行できるようにするにはどうすればよいですか?