Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Spring bean

Tags:

java

spring

I have the following scenario:

  1. Spring project A with multiple bean configurations, including a bean named "searchHelper":
    <bean name="searchHelper" class="com.test.SearchHelperImpl"/>
    where SearchHelperImpl implements "SearchHelper" interface
  2. Spring project B depends on A with a custom SearchHelperBImpl

What I was thinking of making is just copying the whole configuration into the new project and changing what needs to be changed, but that's not convenient and there must be an easier way of doing this.

My question is, how do I override the definition of the "searchHelper" bean to use SearchHelperBImpl instead of SearchHelperImpl? I want to use the same bean name in order for everything that uses this name to use the new implementation. I am using Spring 3.2.2

Thanks

like image 633
OKAN Avatar asked Nov 04 '13 21:11

OKAN


People also ask

Can we override a bean?

@Buchi Yes, it is allowed. Bean from the file read later in sequence will override entirely previous definition which won't be instantiated at all.

How do I override a class in spring?

To make a configuration in Spring Boot, you need to create a class and annotate it with @Configuration . Usually, in the configuration class, you can define a beans object. But if you want to override built-in configuration, you need to create a new class that extends the built-in class.

Can @bean method be private?

The decision to go with package-private visibility was made simply because private visibility is not allowed for @Bean methods due to CGLIB constraints.


1 Answers

You should be able to utilize the primary xml attribute on your bean element.

<bean name="searchHelper" primary="true" class="com.test.SearchHelperBImpl"/>

Alternatively, if you are using JavaConfig, you can utilize the @Primary annotation.

@Primary
@Bean
public SearchHelper searchHelper() {
    return new SearchHelperBImpl();
}
like image 94
nicholas.hauschild Avatar answered Oct 27 '22 09:10

nicholas.hauschild