fortran fortran - 12 days ago 4
Java Question

How to make Spring to pick a subclass in a property reference?

I am trying to use a specialized subclass in a Spring web application for testing.

The application context xml files reference a class in a few bean's properties by the fully qualified class name, like this:

<bean id="blahblah" class="x.y.z.Blah">
<property name="myFooAttribute" ref="x.y.z.Foo"/>
</bean>


and I would like to instantiate and use
x.y.z.Bar
instead of
x.y.z.Foo
, everywhere it is used.

In my test I am using a Java based config and importing the XML configuration (legacy stuff that I don't really want to mess too much around) since it feels more natural when I'm going to be patching things and using mocks declared inline.

@Configuration
@ImportResource({
"classpath:applicationContext-common.xml",
"classpath:app-servlet.xml"
})
static class TestConfig {
static class Bar extends Foo {
//some stuff overridden here
}

}


How can I make all the places that reference to
x.y.z.Foo
use my
Bar
class instead? Preferably without changing the xml files...

Answer

Creating a bean named as the class that you are trying to override works. It can be achieved in the Java style configuration using the Bean annotation.

@Configuration
@ImportResource({
        "classpath:applicationContext-common.xml",
        "classpath:app-servlet.xml"
})
static class TestConfig {
    static class Bar extends Foo {
        //some stuff overridden here
    }
    private Bar myTestBar = new Bar();
    @Bean(name="x.y.z.Foo")
    public Foo getFoo() {
       return myTestBar;
    }
}
Comments