Spring 如果应用程序在给定配置文件上运行,则重写和扩展bean
假设我用@Service注释了mainbean,它被注入到另一个带有@Autowired的服务中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
@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();
}
}