Override xml-defined spring bean in java-based configuration Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Override xml-defined spring bean in java-based configuration without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m extending a complete product called Hippo CMS with my own REST interface. Hippo CMS is using Apache CXF for rest and acquires resources definitions from a spring bean defined somewhere in Hippo CMS sources. This definition look like this:

<bean id="jaxrsRestPlainResourceProviders" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetClass" value="org.apache.commons.collections.ListUtils" />
  <property name="targetMethod" value="union" />
  <property name="arguments">
    <list>
      <ref bean="customRestPlainResourceProviders" />
      <ref bean="defaultRestPlainResourceProviders" />
    </list>
  </property>
</bean>

<bean id="defaultRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
  <property name="sourceList">
    <list>
    </list>
  </property>
</bean>

<!-- Default empty list of custom plain resource providers to be overriden. -->
<bean id="customRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
  <property name="sourceList">
    <list>
    </list>
  </property>
</bean>

I need to override customRestPlainResourceProviders bean with my own bean. It works fine from XML configuration looking like this:

<bean id="customRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
  <property name="sourceList">
    <list>
      <bean class="org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider">
        <constructor-arg>
          <bean class="com.xxx.rest.FolderStructureResource"/>
        </constructor-arg>
      </bean>
    </list>
  </property>
</bean>

But it doesn’t work if I define a bean in Java configuration class (which in the case of other beans works completely fine):

@Bean(name = "customRestPlainResourceProviders")
public ListFactoryBean customRestPlainResourceProviders() {
  ListFactoryBean listFactoryBean = new ListFactoryBean();
  listFactoryBean.setSourceList(
    Lists.newArrayList(
      new SingletonResourceProvider(
        new FolderStructureResource(repository())
      )
    )
  );
  return listFactoryBean;
}

Is there a way to override a bean defined in XML configuration with a bean created in Java configuration class?

Answer

What version of spring are you using? I believe this issues is addressed in 4.2.

We are here to answer your question about Override xml-defined spring bean in java-based configuration - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji