将 xml 和 java 配置与 spring 混合

2022-09-01 18:37:28

我正在构建一个新的应用程序,该应用程序通过java配置而不是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 应该在模块的应用程序Context中声明.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>

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


答案 1

在配置类中,可以通过@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>

答案 2

推荐