Intellij:“无法自动装配。有不止一个‘MyType’类型的bean”与@ConditionalOnProperty

Vit*_*lii 5 intellij-idea

在我的 Spring Boot 应用程序中,IntelliJ 向我显示了警告 Could not autowire. There is more than one bean of 'MyType' type.

实际上有两个 bean,但它们是根据属性定义的

@Service
@ConditionalOnProperty(name = "features.feature1", havingValue = "true")
public class Bean1 implements SomeInterface{

}
Run Code Online (Sandbox Code Playgroud)

而第二个依赖于相同的属性,application.yml但如果它被设置为false

@Service
@ConditionalOnProperty(name = "features.feature1", havingValue = "false", matchIfMissing = true)
public class Bean2 implements SomeInterface{

}
Run Code Online (Sandbox Code Playgroud)

有没有办法让 IntelliJ 理解这一点而不显示警告?项目运行没有问题。

小智 0

对我来说,创建一个结合这些条件的类更容易、更干净,这样我就可以使用它,@ConditionalOnBean例如

@Configuration
@ConditionalOnProperty(name = "features.feature1", havingValue = "false", matchIfMissing = true)
    public class FeatureIsFalse{
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

@Service
@ConditionalOnMissingBean(FeatureIsFalse.class)
public class Bean1 implements SomeInterface{

}
Run Code Online (Sandbox Code Playgroud)

@Service
@ConditionalOnBean(FeatureIsFalse.class)
public class Bean2 implements SomeInterface{

}
Run Code Online (Sandbox Code Playgroud)

让我知道这是否对你有用。