Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如果应用程序在给定配置文件上运行,则重写和扩展bean_Spring_Spring Boot_Spring Bean - Fatal编程技术网

Spring 如果应用程序在给定配置文件上运行,则重写和扩展bean

Spring 如果应用程序在给定配置文件上运行,则重写和扩展bean,spring,spring-boot,spring-bean,Spring,Spring Boot,Spring Bean,假设我用@Service注释了mainbean,它被注入到另一个带有@Autowired的服务中 @Service @Order(100) class MainService() { fun helloWorld() = "Hello" } 我想在使用另一个配置文件fg运行时扩展此服务。(“习俗”)。因此,我的服务如下: @Service("mainService") @Order(1) class CustomService: MainService() { override

假设我用@Service注释了mainbean,它被注入到另一个带有@Autowired的服务中

@Service
@Order(100)
class MainService() {
   fun helloWorld() = "Hello"
}
我想在使用另一个配置文件fg运行时扩展此服务。(“习俗”)。因此,我的服务如下:

@Service("mainService")
@Order(1)
class CustomService: MainService() {
    override fun helloWorld() = "Hello custom"
}
但我有一个例外:

原因:org.springframework.context.annotation.ConflictingBeanDefinitionException:为bean类[mainService]指定的注释bean名称“mainService”与相同名称和类[CustomService]的现有不兼容bean定义冲突


你知道我如何用同一个名字扩展和覆盖bean吗?这是因为我需要将其自动连接到其他地方

您可以使用配置bean来执行此操作:

@Configuration
@Profile("dev")
public class MainServiceDev {

    @Bean
    public MainService mainService() {
        return new MainService();
    }

}

@Configuration
@Profile("custom")
public class MainServiceCustom {

    @Bean
    public CustomService customService() {
        return new CustomService();
    }

}