覆盖Spring bean

OKA*_*KAN 9 java spring

我有以下场景:

  1. 具有多个bean配置的Spring项目A,包括名为"searchHelper"的bean:
    <bean name="searchHelper" class="com.test.SearchHelperImpl"/>
    其中SearchHelperImpl实现"SearchHelper"接口
  2. Spring项目B依赖于A和自定义的SearchHelperBImpl

我想要做的只是将整个配置复制到新项目中并更改需要更改的内容,但这样做并不方便,必须有一种更简单的方法.

我的问题是,如何覆盖"searchHelper"bean的定义以使用SearchHelperBImpl而不是SearchHelperImpl?我想使用相同的bean名称,以便使用此名称的所有内容都使用新的实现.我使用的是Spring 3.2.2

谢谢

nic*_*ild 10

您应该能够primarybean元素上使用xml属性.

<bean name="searchHelper" primary="true" class="com.test.SearchHelperBImpl"/>
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的是JavaConfig,则可以使用@Primary注释.

@Primary
@Bean
public SearchHelper searchHelper() {
    return new SearchHelperBImpl();
}
Run Code Online (Sandbox Code Playgroud)


dig*_*oel 7

Spring的一个有趣的"功能"(有些人认为它是一个bug)是配置中稍后声明的具有相同名称的bean将覆盖之前在配置中声明的bean.因此,如果您的项目B依赖于A,并且A中的配置包含在B中,并且B在A配置之后使用相同的名称定义bean,那么B实例将"获胜",这就是您将获得的实例.

我不建议取决于这种行为,但会得到关于主要注释的答案.我只是认为我会提出这个问题,所以你会意识到,即使没有主要的,或者如果项目A中的那个也是主要的,你会知道最新的定义获胜.


inf*_*k01 2

注意
这个答案涉及如何避免重复的bean 定义。对于覆盖,请参阅nicholas.hauschild 的答案


避免复制的更有效解决方案是将两个项目共用的所有 bean 放在单独的 XML 配置文件中,例如“common-beans.xml”。在项目 B(以及需要这些 bean 的任何其他项目)的配置 XML 文件中,您可以像这样导入该文件:

<import resource="common-beans.xml" />


简单的例子

示例上下文.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
    
    <!-- 
         Assuming common-beans.xml is a Spring config file
         that contains the definitions you need to use
         in the current project. 
    -->
    <import resource="common-beans.xml" />
    
    <!-- Defining a bean with the implementaion you need -->
    <bean name="searchHelper" class="com.test.SearchHelperBImpl"/>
    
    <!-- Some other configurations if needed -->
    
</beans>
Run Code Online (Sandbox Code Playgroud)

有用的阅读: