簡體   English   中英

Spring Java配置指定的Bean不會初始化

[英]Spring Java config specified Beans won't initialize

我已經閱讀了Spring In Action,並且更喜歡Java配置而不是XML配置。 因此,我使用Java config編寫了我的應用程序,但是我們的部署環境要求我使用XML config。 所以我寫了一個XML配置文件,它唯一的功能就是導入根Java配置文件。

Java配置代碼如下所示:

package com.somegroup.app;
@Configuration
@ComponentScan(basePackages = "com.tianchengsys.crawlers.cqs")
public class AppCtxConfig {

    @Bean
    public SomeType aSomeType() {
           return new SomeType()
    }

}

XML配置如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://code.alibabatech.com/schema/dubbo
    http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <context:annotation-config />

    <bean class="com.somegroup.app.AppCtxConfig" lazy-init="false" />

</beans>

當我在Eclipse中創建ClasspathXmlContext("classpath:spring-context.xml")時,將初始化Java配置中定義的SomeType Bean,並將其注冊到Spring ApplicationContext中。 但是,當我部署此應用程序時(所有依賴項都在lib目錄中),在XML配置中定義的AppCtxConfig bean僅被視為普通bean(而不是配置)。

它已創建,但是其中定義的bean未初始化。 Spring有時警告Java配置中的someType方法應該是靜態的。 我確實將其更改為靜態,也沒有用。

這是因為您正在將AppCtxConfig創建為常規bean,但事實並非如此。

如評論員所建議,將component-scan on添加並設置base-package到config類所在的包中:

<!-- Scan the JavaConfig -->
<context:component-scan base-package="com.somegroup.app" />

如果您的應用程序包是根包,其中包含所有子包,請添加一個新的配置包,然后將AppCtxConfig其中。

因此添加:

<!-- Scan the config package with AppCtxConfig inside it -->
<context:component-scan base-package="com.somegroup.app.config" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM