小编Wil*_*ill的帖子

如何使用Annotations覆盖xml中定义的spring bean?

我有一个已overrideBean定义的bean spring.xml,我想用注释覆盖它.我尝试了以下来覆盖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;
    }

}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,spring.xml配置中的bean 始终被实例化并由context.getBean调用返回.

可以通过包含另一个XML配置文件来覆盖bean,@ImportResource但是我希望找到一个使用注释的解决方案更干净.

spring spring-annotations

7
推荐指数
2
解决办法
4242
查看次数

标签 统计

spring ×1

spring-annotations ×1