Search code examples
springspring-annotations

How do you override a spring bean defined in xml using Annotations?


I have an existing bean overrideBean defined in spring.xml which I would like to override using annotations. I have tried the following to override the bean:

@Configuration
@ImportResource({"/spring.xml"})
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DdwMain.class);

        Object o = context.getBean("overrideBean");
        // o should be null but it is not
    }

    @Bean(name="overrideBean")
    public OverrideBean overrideBean() {
        return null;
    }

}

Using the above code the bean from the spring.xml config is always instantiated and returned by the context.getBean call.

The bean can be overridden by including another XML config file in the @ImportResource however I would prefer to find a solution using annotations would be cleaner.


Solution

  • Usually xml-registered beans have precedence. So you can override annotated beans with xml-configured ones but you are trying to do it the other way around. Can you not use a different bean name and select it among multiple candidates by using the @Qualifier annotation?

    Most of the time combining xml with autoscanning is error-prone.