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.
Main
class the Spring@Configuration
class? What happens if you instantiate the Spring context using a different@Configuration
class`?ImportResource
is done only after all bean definitions from the@Configuration
class are read. So the definition replacement is done in the opposite way than you are expecting. I can imagine that you can find related feature request in Spring Jira.