1

私の古い 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 コンテキストでテストを実行できるようにするにはどうすればよいですか?

4

1 に答える 1

0

M. Deinumがコメントで示した解決策は正しいですが、ヒントが得られなかった可能性があります。あなたが言うとき: useDefaultFilters = falseそして、 Springが次のようなステレオタイプの注釈を探すのを妨げるexcludeFilters = {@Filter(value = org.springframework.stereotype.Controller.class)} ため、何も見つかりませんuseDefaultFilters = false@Controller, @Service ...

Spring API ドキュメントへのリンク

于 2014-10-24T09:31:37.560 に答える