2017-10-20 131 views
0

我讀過Spring In Action,並且更喜歡Java config over XML config。所以我使用Java配置來編寫我的應用程序,但是我們的部署環境要求我使用XML配置。所以我寫了一個XML配置文件,它的唯一功能是導入根配置文件。Spring Java配置指定bean不會初始化

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是初始化並註冊以彈出ApplicationContext。但是當我部署這個應用程序時(所有依賴關係都在lib目錄中),在XML配置中定義的AppCtxConfig bean只被視爲一個普通的bean(不是配置)。

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

+0

你嘗試使用<上下文:組分掃描基包= 「com.somegroup.app」/>?你可以參考[這篇文章如何在config.xml中引用java配置](http://memorynotfound.com/mixing-xml-java-config-spring/) – BharaniK

回答

0

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

由於評註的建議,添加組件,掃描並基本包設爲您的配置類位於包:

<!-- 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" />