@条件配置-Spring找不到我的豆子

时间:2018-12-11 18:14:33

标签: spring

我有一个接口和两个在接口中实现的类:

public interface Connector {
    void connect();
}

public class ConnectorOne implements Connector {
    @Override
    public void connect() {
        System.out.println("connector one");
    }
}

public class ConnectorTwo implements Connector {
    @Override
    public void connect() {
        System.out.println("connector two");
    }
}

我有一个constroller,需要在其中注入我的一个类的实例:

@Controller
public class ConnectorController {

    public ConnectorController(Connector connector) {
        connector.connect();
    }
}

要确定要使用哪些类,我正在使用环境变量:

public class ConnectorOneCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String connectorType = System.getProperty("connector");
        return (connectorType != null && connectorType.equalsIgnoreCase("one"));
    }
}

public class ConnectorTwoCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        String connectorType = System.getProperty("connector");
        return (connectorType != null && connectorType.equalsIgnoreCase("two"));
    }
}

@Configuration
public class ConnectorConfig {

    @Bean
    @Conditional(ConnectorOneCondition.class)
    public Connector getConnectorOne() {
        return new ConnectorOne();
    }

    @Bean
    @Conditional(ConnectorTwoCondition.class)
    public Connector getConnectorTwo() {
        return new ConnectorTwo();
    }
}

但是当我启动应用程序时,我收到消息:

  

guru.springframework.controllers.ConnectorController中构造函数的参数0需要一个类型为'guru.springframework.services.Connector'的bean。

为什么Spring在ConnectorConfig类中找不到两个bean?我该如何解决?

0 个答案:

没有答案