覆盖 java 配置中的 bean 定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23547482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Override bean definition in java config
提问by maks
I have a configuartion class
我有一个配置类
@Configuration
public class FooConfig{
@Bean
public FooService fooService() { ... }
@Bean
public AbcService abcService() { ... }
}
That class is defined in a lib that I can't change. I have a project where FooService
is used in many places. In my project I have another configuration class
该类是在我无法更改的库中定义的。我有一个FooService
在很多地方使用的项目。在我的项目中,我有另一个配置类
@Configuration
@Import({
FooConfig.class,
})
public class BarConfig{
@Autowired AbcService abc;
...
}
AbcService
is used here because there are services which depends on that service and that services are declared in BarConfig
. However, FooService
is not used here(it is used only in controllers)
AbcService
在这里使用是因为存在依赖于该服务的服务并且该服务在BarConfig
. 但是,FooService
这里不使用(仅在控制器中使用)
I need to change the implementation of FooService
. Can I define new FooService
bean in BarConfig
? Will it override already present definition which is imported via FooConfig
?
我需要更改FooService
. 我可以FooService
在 中定义新beanBarConfig
吗?它会覆盖通过 导入的已经存在的定义FooConfig
吗?
回答by Centonni
You can redefine the same bean name multiple times, the spring container will take the last bean definition processed for a given name to be the one that wins.
In your case, as the core project that contains the configuration you can't change does not depend on any of the beans you define in your project, it will work fine if you redefine the FooService
bean.
there was lot of answers about how to override bean defintions before, you can have a look to have more informations.
您可以多次重新定义相同的 bean 名称,spring 容器会将为给定名称处理的最后一个 bean 定义作为获胜的 bean 定义。在您的情况下,由于包含您无法更改的配置的核心项目不依赖于您在项目中定义的任何 bean,如果您重新定义FooService
bean.
有很多关于如何覆盖 bean 定义的答案,它将正常工作之前,你可以看看有更多的信息。