Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override an imported resource using Spring @Configuration?

Is it possible to override imported resources using Spring annotation configuration?

The configuration class:

@Configuration
@ImportResource({"classpath:applicationContext.xml"})
public class CoreConfiguration {

    @Resource(name = "classA")
    private ClassA classA;

    @Bean(name = "nameIWantToOverride")
    private ClassB classB() {
       return new ClassB("different setting");
    }

}

The applicationContext.xml includes:

<bean name="classA" class="a.b.c.ClassA">
     <property name="nameIWantToOverride" ref="classB" />
</bean>

If classA has a classB field but I want it to use the ClassB I define in my configuration class, is that possible? I tried switching the order but that didn't help. It seems XML takes precedence as when I run a simple test of instantiating the config, it never reaches the classB method. If I change the name so it doesn't match the bean in the xml file, then it does reach the classB method.

I've seen where it can work the other way: Can spring framework override Annotation-based configuration with XML-based configuration? but what about this direction? Since this is the newer way of doing things, I would think it you'd be able to do this.

What can I do to resolve this?

Edit: Updated with XML. Assume classA has multiple fields but I just want to replace the one.

like image 952
AHungerArtist Avatar asked May 10 '12 13:05

AHungerArtist


1 Answers

You cannot override spring xml configuration using annotation.

Spring XML configuration always takes precedence to annotation configuration

like image 117
Sudhakar Avatar answered Sep 23 '22 14:09

Sudhakar