java spring-boot @ConditionalOnClass 如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25789907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:41:47  来源:igfitidea点击:

How does spring-boot @ConditionalOnClass work?

javaspringspring-boot

提问by membersound

How exactly does the @ConditionalOnClassannotation work?

@ConditionalOnClass注释究竟是如何工作的?

My goal is to load a specific bean only if the jarproviding this class is included in the classpath.

我的目标是仅当jar提供此类包含在类路径中时才加载特定的 bean 。

I thought the I could annotate a @Beanwith @ConditionalOnClass(MyService.class)and declaring the dependency in maven as optional:

我认为我可以注释一个@Beanwith@ConditionalOnClass(MyService.class)并将 maven 中的依赖声明为可选:

<dependency>
    <groupId>de.my</groupId>
    <artifactId>my-framework<artifactId>
    <optional>true</optional>
</dependency>

@Bean
@ConditionalOnClass(MyService.class)
public MyConditionalBean statistics() {
    return new MyConditionalBean();
}

Now, anyone having my-frameworkas dependency should get that bean automatically wired. But anyone not having the dependency should skip it.

现在,任何具有my-framework依赖项的人都应该自动连接该 bean。但是任何没有依赖性的人都应该跳过它。

But when I start the app, I get the following error:

但是当我启动应用程序时,出现以下错误:

Caused by: java.lang.ClassNotFoundException: de.MyService.class
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702) ~[catalina.jar:7.0.50]
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547) ~[catalina.jar:7.0.50]

So I'm probably doing something wrong. How can I then create the bean conditional on the dependency jars and the classes contained in the classpath?

所以我可能做错了什么。然后,如何以依赖项 jar 和类路径中包含的类为条件创建 bean?

From the spring docs:

来自 spring 文档:

The classes that must be present. Since this annotation parsed by loading class bytecode it is safe to specify classes here that may ultimately not be on the classpath.

必须存在的类。由于此注释是通过加载类字节码来解析的,因此在此处指定最终可能不在类路径上的类是安全的。

But the error states different...

但错误状态不同......

采纳答案by Artem Bilan

Good catch!

接得好!

You can use on @Beanmethod level, but in that case you have to specify your class as a String literal:

您可以在@Bean方法级别使用,但在这种情况下,您必须将您的类指定为字符串文字:

@Bean
@ConditionalOnClass(name ="de.MyService")
public MyConditionalBean statistics() {
    return new MyConditionalBean();
}

I don't remeber already "why", but it is from an existing code of Spring Boot sources.

我已经不记得“为什么”了,但它来自 Spring Boot 源的现有代码。