【问题标题】:Mixing xml and java config with spring将xml和java配置与spring混合
【发布时间】:2013-10-22 07:42:54
【问题描述】:

我正在构建一个新的应用程序,它通过 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>

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

【问题讨论】:

    标签: java xml spring


    【解决方案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>
    

    【讨论】:

    • 我已经拿到了第二部分,但感谢您的提醒。至于 context.xml,我只需要导入它,剩下的就交给我了吗?还是我需要以某种方式“运行”它?
    • ApplicationContext 引导加载@Configuration 类时,它会扫描并自动加载它。
    • @ImportResource 将运行它。
    猜你喜欢
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2011-10-05
    相关资源
    最近更新 更多