spring-boot @ConditionalOnClass如何工作? [英] How does spring-boot @ConditionalOnClass work?

查看:1141
本文介绍了spring-boot @ConditionalOnClass如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@ConditionalOnClass注释的工作原理如何?

How exactly does the @ConditionalOnClass annotation work?

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

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

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

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

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

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

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

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

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

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]

所以我可能做错了什么.然后,如何在依赖罐和类路径中包含的类的条件下创建bean?

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?

从spring文档中获取:

From the spring docs:

必须存在的类.由于此注释由 加载类字节码时,可以在此处指定可能安全的类 最终不在类路径上.

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...

推荐答案

好收获!

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

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

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

我还没有记住为什么",但这是从Spring Boot源代码的现有代码中得出的.

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

这篇关于spring-boot @ConditionalOnClass如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆