Spring Java配置指定bean不会初始化
问题描述:
我读过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方法应该是静态的。我确实将其改为静态,但它也无效。
答
这是因为您正在创建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" />
你尝试使用?你可以参考[这篇文章如何在config.xml中引用java配置](http://memorynotfound.com/mixing-xml-java-config-spring/) – BharaniK