@ConditionalOnProperty Bean 配置未按预期工作

问题描述 投票:0回答:1

对于一个简单的 Spring Boot 应用程序,在尝试有条件实例化 beans 时,我遇到了意外的行为。

我在我的

application.yml
中定义了条件标志:

service.enable=true

然后我创建了

ServiceMesh.java
接口,该接口应该由serviceA和serviceB实现,如下所示:

public interface ServiceMesh {
}

public class ServiceA implements ServiceMesh {
    // ... code
}

public class ServiceB implements ServiceMesh {
    // ... code
}

我还定义了一个配置类:

@Configuration
public class ConditionOnPropertyConfiguration {

@Bean
@ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "true")
public ServiceMesh from(){
    return new ServiceA();
  }

@Bean
@ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "false")
public ServiceMesh from(Environment env){
    return new ServiceB();
  }
}

运行我的主类时:

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

我收到此错误:

没有“com.example.demo.service.ServiceMesh”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注释:{}

预期行为是启动应用程序

java spring spring-boot conditional-statements
1个回答
1
投票

将方法名称

from
更改为
serviceA
serviceB
。我已将属性定义从
service.enable=true
更改为
service.enabled=true

    @Bean
    @ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "true")
    public ServiceMesh serviceA() {
        return new ServiceA();
    }

    @Bean
    @ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "false")
    public ServiceMesh serviceB() {
        return new ServiceB();
    }
© www.soinside.com 2019 - 2024. All rights reserved.