我有一个现有的豆定义spring.xml
,我想使用注释重写。我曾尝试以下覆盖豆:如何重写使用注解在xml中定义的spring 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;
}
}
从spring.xml
配置使用上面的代码中的豆总是实例化和由context.getBean
调用返回。
可以通过在@ImportResource
中包含另一个XML配置文件来覆盖该bean,但是我希望找到一个使用注释的解决方案将更清晰。
为什么您的'Main'类是Spring'@ Configuration'类?如果使用不同的'@ Configuration'类实例化Spring上下文会发生什么? – 2013-08-23 13:50:10
'ImportResource'只有在读取了'@ Configuration'类的所有bean定义后才能完成。所以定义替换的方式与你所期望的相反。我可以想象你可以在Spring Jira中找到相关的功能请求。 –
https://jira.springsource.org/browse/SPR-7341 –