25

我正在构建一个通过 java config 而不是 xml 配置 spring 的新应用程序。此应用程序依赖于使用 xml 样式配置的模块。当我尝试启动我的应用程序时,我收到以下错误:

No qualifying bean of type [com.myModule.myServiceImp] 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)}

这个 bean 应该在模块的 applicationContext.xml 中声明。处理这个问题的正确方法是什么?如果我在应用程序的 web.xml 中将应用程序上下文串在一起,我尝试简单地添加它:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:com/myModule/appbase-context.xml
            com.myApp.AppConfig
        </param-value>
    </context-param>

但我仍然遇到同样的错误。这样做的正确方法是什么?

4

1 回答 1

48

在您的配置类中,您可以通过@ImportResource注解导入 xml 配置。

像这样的东西:

@Configuration
@ImportResource({"classpath:appbase-context.xml"})
public class AppConfig {
    // @Bean definitions here...
}

请记住,当您使用 Spring 的 Java 配置时,您需要指定一个附加context-param说明用于您的应用程序上下文的类:

<context-param>
    <param-name>contextClass</param-name>
    <param-value>
        org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
</context-param>
于 2013-10-14T17:09:07.130 回答