如果bean不存在,请不要使spring容器失败

时间:2016-04-11 16:35:20

标签: java spring

我在项目上有3个模块。其中一人打电话给common。在这个模块中,我试图启动Spring容器。其中一个bean存在于另一个模块(webapp)中,我还有一个模块testapp。所以现在,在服务器上部署项目(webapp和common)之后一切正常,但如果我尝试部署common和testapp,它会失败,但例外:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class[...]

我想知道是否有可能忽略不存在的bean并运行容器?我正在使用xml配置,没有注释。由于业务逻辑,它应该是xml

1 个答案:

答案 0 :(得分:1)

利用Spring配置文件确定何时应实例化特定bean。例如,您可以拥有两个配置文件Web(用于common + webapp)和test(用于common + testapp)

然后在您的应用程序上下文中,xml配置定义您的bean,如下所示

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

   <!-- define common beans here-->
     <beans profile="test">
         <!-- define test beans here-->
     </beans>
     <beans profile="web">
        <!-- define web beans here-->
     </beans>
</beans>

然后,根据您启动应用程序的方式,您需要提供名为spring.profiles.active的系统属性以提供要使用的配置文件。

例如-Dspring.profiles.active = web或-Dspring.profiles.active = test

相关问题