前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Spring Boot是如何实现自动配置的

Spring Boot是如何实现自动配置的

作者头像
Bug开发工程师
发布于 2018-07-23 10:39:42
发布于 2018-07-23 10:39:42
1.1K00
代码可运行
举报
文章被收录于专栏:码农沉思录码农沉思录
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
作者:sylvanassun
原文:sylvanassun.github.io/2018/01/08/2018-01-08-spring_boot_auto_configure/

Spring Boot 是 Spring 旗下众多的子项目之一,其理念是约定优于配置,它通过实现了自动配置(大多数用户平时习惯设置的配置作为默认配置)的功能来为用户快速构建出标准化的应用。Spring Boot 的特点可以概述为如下几点:

  • 内置了嵌入式的 Tomcat、Jetty 等 Servlet 容器,应用可以不用打包成War 格式,而是可以直接以 Jar 格式运行。
  • 提供了多个可选择的 ”starter ” 以简化Maven的依赖管理(也支持Gradle),让您可以按需加载需要的功能模块。
  • 尽可能地进行自动配置,减少了用户需要动手写的各种冗余配置项,Spring Boot 提倡无XML配置文件的理念,使用Spring Boot生成的应用完全不会生成任何配置代码与XML配置文件。
  • 提供了一整套的对应用状态的监控与管理的功能模块(通过引入spring-boot-starter-actuator),包括应用的线程信息、内存信息、应用是否处于健康状态等,为了满足更多的资源监控需求,Spring Cloud中的很多模块还对其进行了扩展。

有关Spring Boot的使用方法就不做多介绍了,如有兴趣请自行阅读官方文档Spring Boot或其他文章。

如今微服务的概念愈来愈热,转型或尝试微服务的团队也在如日渐增,而对于技术选型,Spring Cloud是一个比较好的选择,它提供了一站式的分布式系统解决方案,包含了许多构建分布式系统与微服务需要用到的组件,例如服务治理、API网关配置中心、消息总线以及容错管理等模块。可以说,Spring Cloud”全家桶”极其适合刚刚接触微服务的团队。似乎有点跑题了,不过说了这么多,我想要强调的是,Spring Cloud中的每个组件都是基于Spring Boot构建的,而理解了Spring Boot的自动配置的原理,显然也是有好处的。

Spring Boot的自动配置看起来神奇,其实原理非常简单,背后全依赖于@Conditional注解来实现的。

什么是@Conditional?

@Conditional是由Spring 4提供的一个新特性,用于根据特定条件来控制Bean的创建行为。而在我们开发基于Spring的应用的时候,难免会需要根据条件来注册Bean。

例如,你想要根据不同的运行环境,来让Spring注册对应环境的数据源Bean,对于这种简单的情况,完全可以使用@Profile注解实现,就像下面代码所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Configuration
public class AppConfig {
   @Bean
   @Profile("DEV")
   public DataSource devDataSource() {
       ...
   }
    
   @Bean
   @Profile("PROD")
   public DataSource prodDataSource() {
       ...
   }
}

剩下只需要设置对应的Profile属性即可,设置方法有如下三种:

  • 通过context.getEnvironment().setActiveProfiles("PROD")来设置Profile属性。
  • 通过设定jvm的spring.profiles.active参数来设置环境(Spring Boot中可以直接在application.properties配置文件中设置该属性)。
  • 通过在DispatcherServlet的初始参数中设置。
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<servlet>
   <servlet-name>dispatcher</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
       <param-name>spring.profiles.active</param-name>
       <param-value>PROD</param-value>
   </init-param>
</servlet>

但这种方法只局限于简单的情况,而且通过源码我们可以发现@Profile自身也使用了@Conditional注解。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package org.springframework.context.annotation;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({ProfileCondition.class}) // 组合了Conditional注解
public @interface Profile {
   String[] value();
}
package org.springframework.context.annotation;
class ProfileCondition implements Condition {
   ProfileCondition() {
   }
   // 通过提取出@Profile注解中的value值来与profiles配置信息进行匹配
   public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
       if(context.getEnvironment() != null) {
           MultiValueMap attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
           if(attrs != null) {
               Iterator var4 = ((List)attrs.get("value")).iterator();
               Object value;
               do {
                   if(!var4.hasNext()) {
                       return false;
                   }
                   value = var4.next();
               } while(!context.getEnvironment().acceptsProfiles((String[])((String[])value)));
               return true;
           }
       }
       return true;
   }
}

在业务复杂的情况下,显然需要使用到@Conditional注解来提供更加灵活的条件判断,例如以下几个判断条件:

  • 在类路径中是否存在这样的一个类。
  • 在Spring容器中是否已经注册了某种类型的Bean(如未注册,我们可以让其自动注册到容器中,上一条同理)。
  • 一个文件是否在特定的位置上。
  • 一个特定的系统属性是否存在。
  • 在Spring的配置文件中是否设置了某个特定的值。

举个栗子,假设我们有两个基于不同数据库实现的DAO,它们全都实现了UserDao,其中JdbcUserDAO与MySql进行连接,MongoUserDAO与MongoDB进行连接。现在,我们有了一个需求,需要根据命令行传入的系统参数来注册对应的UserDao,就像java -jar app.jar -DdbType=MySQL会注册JdbcUserDao,而java -jar app.jar -DdbType=MongoDB则会注册MongoUserDao。使用@Conditional可以很轻松地实现这个功能,仅仅需要在你自定义的条件类中去实现Condition接口,让我们来看下面的代码。(以下案例来自:https://dzone.com/articles/how-springboot-autoconfiguration-magic-works)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public interface UserDAO {
   ....
}
public class JdbcUserDAO implements UserDAO {
   ....
}
public class MongoUserDAO implements UserDAO {
   ....
}
public class MySQLDatabaseTypeCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
       String enabledDBType = System.getProperty("dbType"); // 获得系统参数 dbType
       // 如果该值等于MySql,则条件成立
       return (enabledDBType != null && enabledDBType.equalsIgnoreCase("MySql"));
   }
}
// 与上述逻辑一致
public class MongoDBDatabaseTypeCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
       String enabledDBType = System.getProperty("dbType");
       return (enabledDBType != null && enabledDBType.equalsIgnoreCase("MongoDB"));
   }
}
// 根据条件来注册不同的Bean
@Configuration
public class AppConfig {
   @Bean
   @Conditional(MySQLDatabaseTypeCondition.class)
   public UserDAO jdbcUserDAO() {
       return new JdbcUserDAO();
   }
    
   @Bean
   @Conditional(MongoDBDatabaseTypeCondition.class)
   public UserDAO mongoUserDAO() {
       return new MongoUserDAO();
   }
}

现在,我们又有了一个新需求,我们想要根据当前工程的类路径中是否存在MongoDB的驱动类来确认是否注册MongoUserDAO。为了实现这个需求,可以创建检查MongoDB驱动是否存在的两个条件类。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class MongoDriverPresentsCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
       try {
           Class.forName("com.mongodb.Server");
           return true;
       } catch (ClassNotFoundException e) {
           return false;
       }
   }
}
public class MongoDriverNotPresentsCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
       try {
           Class.forName("com.mongodb.Server");
           return false;
       } catch (ClassNotFoundException e) {
           return true;
       }
   }
}

假如,你想要在UserDAO没有被注册的情况下去注册一个UserDAOBean,那么我们可以定义一个条件类来检查某个类是否在容器中已被注册。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class UserDAOBeanNotPresentsCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
       UserDAO userDAO = conditionContext.getBeanFactory().getBean(UserDAO.class);
       return (userDAO == null);
   }
}

如果你想根据配置文件中的某项属性来决定是否注册MongoDAO,例如app.dbType是否等于MongoDB,我们可以实现以下的条件类。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class MongoDbTypePropertyCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
       String dbType = conditionContext.getEnvironment().getProperty("app.dbType");
       return "MONGO".equalsIgnoreCase(dbType);
   }
}

我们已经尝试并实现了各种类型的条件判断,接下来,我们可以选择一种更为优雅的方式,就像@Profile一样,以注解的方式来完成条件判断。首先,我们需要定义一个注解类。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(DatabaseTypeCondition.class)
public @interface DatabaseType {
   String value();
}

具体的条件判断逻辑在DatabaseTypeCondition类中,它会根据系统参数dbType来判断注册哪一个Bean。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class DatabaseTypeCondition implements Condition {
   @Override
   public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
       Map<String, Object> attributes = metadata
                                           .getAnnotationAttributes(DatabaseType.class.getName());
       String type = (String) attributes.get("value");
       // 默认值为MySql
       String enabledDBType = System.getProperty("dbType", "MySql");
       return (enabledDBType != null && type != null && enabledDBType.equalsIgnoreCase(type));
   }
}

最后,在配置类应用该注解即可。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Configuration
@ComponentScan
public class AppConfig {
   @Bean
   @DatabaseType("MySql")
   public UserDAO jdbcUserDAO() {
       return new JdbcUserDAO();
   }
   @Bean
   @DatabaseType("mongoDB")
   public UserDAO mongoUserDAO() {
       return new MongoUserDAO();
   }
}

AutoConfigure源码分析

通过了解@Conditional注解的机制其实已经能够猜到自动配置是如何实现的了,接下来我们通过源码来看看它是怎么做的。本文中讲解的源码基于Spring Boot 1.5.9版本(最新的正式版本)。

使用过Spring Boot的童鞋应该都很清楚,它会替我们生成一个入口类,其命名规格为ArtifactNameApplication,通过这个入口类,我们可以发现一些信息。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
       SpringApplication.run(DemoApplication.class, args);
   }
}

首先该类被@SpringBootApplication注解修饰,我们可以先从它开始分析,查看源码后可以发现它是一个包含许多注解的组合注解。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
   excludeFilters = {@Filter(
   type = FilterType.CUSTOM,
   classes = {TypeExcludeFilter.class}
), @Filter(
   type = FilterType.CUSTOM,
   classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
   @AliasFor(
       annotation = EnableAutoConfiguration.class,
       attribute = "exclude"
   )
   Class<?>[] exclude() default {};
   @AliasFor(
       annotation = EnableAutoConfiguration.class,
       attribute = "excludeName"
   )
   String[] excludeName() default {};
   @AliasFor(
       annotation = ComponentScan.class,
       attribute = "basePackages"
   )
   String[] scanBasePackages() default {};
   @AliasFor(
       annotation = ComponentScan.class,
       attribute = "basePackageClasses"
   )
   Class<?>[] scanBasePackageClasses() default {};
}

该注解相当于同时声明了@Configuration、@EnableAutoConfiguration与@ComponentScan三个注解(如果我们想定制自定义的自动配置实现,声明这三个注解就足够了),而@EnableAutoConfiguration是我们的关注点,从它的名字可以看出来,它是用来开启自动配置的,源码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
   String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
   Class<?>[] exclude() default {};
   String[] excludeName() default {};
}

我们发现@Import(Spring 提供的一个注解,可以导入配置类或者Bean到当前类中)导入了EnableAutoConfigurationImportSelector类,根据名字来看,它应该就是我们要找到的目标了。不过查看它的源码发现它已经被Deprecated了,而官方API中告知我们去查看它的父类AutoConfigurationImportSelector。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/** @deprecated */
@Deprecated
public class EnableAutoConfigurationImportSelector extends AutoConfigurationImportSelector {
   public EnableAutoConfigurationImportSelector() {
   }
   protected boolean isEnabled(AnnotationMetadata metadata) {
       return this.getClass().equals(EnableAutoConfigurationImportSelector.class)?((Boolean)this.getEnvironment().getProperty("spring.boot.enableautoconfiguration", Boolean.class, Boolean.valueOf(true))).booleanValue():true;
   }
}

由于AutoConfigurationImportSelector的源码太长了,这里我只截出关键的地方,显然方法selectImports是选择自动配置的主入口,它调用了其他的几个方法来加载元数据等信息,最后返回一个包含许多自动配置类信息的字符串数组。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public String[] selectImports(AnnotationMetadata annotationMetadata) {
   if(!this.isEnabled(annotationMetadata)) {
       return NO_IMPORTS;
   } else {
       try {
           AutoConfigurationMetadata ex = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
           AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
           List configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
           configurations = this.removeDuplicates(configurations);
           configurations = this.sort(configurations, ex);
           Set exclusions = this.getExclusions(annotationMetadata, attributes);
           this.checkExcludedClasses(configurations, exclusions);
           configurations.removeAll(exclusions);
           configurations = this.filter(configurations, ex);
           this.fireAutoConfigurationImportEvents(configurations, exclusions);
           return (String[])configurations.toArray(new String[configurations.size()]);
       } catch (IOException var6) {
           throw new IllegalStateException(var6);
       }
   }
}

重点在于方法getCandidateConfigurations()返回了自动配置类的信息列表,而它通过调用SpringFactoriesLoader.loadFactoryNames()来扫描加载含有META-INF/spring.factories文件的jar包,该文件记录了具有哪些自动配置类。(建议还是用IDE去看源码吧,这些源码单行实在太长了,估计文章中的观看效果很差)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
   List configurations = SpringFactoriesLoader
                                       .loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
   Assert.notEmpty(configurations, "No auto configuration classes 
   found in META-INF spring.factories. 
   If you are using a custom packaging, make sure that file is correct.");
   return configurations;
}
    
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
   String factoryClassName = factoryClass.getName();
   try {
       Enumeration ex = classLoader != null?classLoader.getResources("META-INF/spring.factories"):ClassLoader.getSystemResources("META-INF/spring.factories");
       ArrayList result = new ArrayList();
       while(ex.hasMoreElements()) {
           URL url = (URL)ex.nextElement();
           Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
           String factoryClassNames = properties.getProperty(factoryClassName);
           result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
       }
       return result;
   } catch (IOException var8) {
       throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() + "] factories from location [" + "META-INF/spring.factories" + "]", var8);
   }
}

自动配置类中的条件注解

接下来,我们在spring.factories文件中随便找一个自动配置类,来看看是怎样实现的。我查看了MongoDataAutoConfiguration的源码,发现它声明了@ConditionalOnClass注解,通过看该注解的源码后可以发现,这是一个组合了@Conditional的组合注解,它的条件类是OnClassCondition。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Configuration
@ConditionalOnClass({Mongo.class, MongoTemplate.class})
@EnableConfigurationProperties({MongoProperties.class})
@AutoConfigureAfter({MongoAutoConfiguration.class})
public class MongoDataAutoConfiguration {
   ....
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnClassCondition.class})
public @interface ConditionalOnClass {
   Class<?>[] value() default {};
   String[] name() default {};
}

然后,我们开始看OnClassCondition的源码,发现它并没有直接实现Condition接口,只好往上找,发现它的父类SpringBootCondition实现了Condition接口。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class OnClassCondition extends SpringBootCondition implements AutoConfigurationImportFilter, BeanFactoryAware, BeanClassLoaderAware {
   .....
}
public abstract class SpringBootCondition implements Condition {
   private final Log logger = LogFactory.getLog(this.getClass());
   public SpringBootCondition() {
   }
   public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
       String classOrMethodName = getClassOrMethodName(metadata);
       try {
           ConditionOutcome ex = this.getMatchOutcome(context, metadata);
           this.logOutcome(classOrMethodName, ex);
           this.recordEvaluation(context, classOrMethodName, ex);
           return ex.isMatch();
       } catch (NoClassDefFoundError var5) {
           throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to " + var5.getMessage() + " not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)", var5);
       } catch (RuntimeException var6) {
           throw new IllegalStateException("Error processing condition on " + this.getName(metadata), var6);
       }
   }
   public abstract ConditionOutcome getMatchOutcome(ConditionContext var1, AnnotatedTypeMetadata var2);
}

SpringBootCondition实现的matches方法依赖于一个抽象方法this.getMatchOutcome(context, metadata),我们在它的子类OnClassCondition中可以找到这个方法的具体实现。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
   ClassLoader classLoader = context.getClassLoader();
   ConditionMessage matchMessage = ConditionMessage.empty();
   // 找出所有ConditionalOnClass注解的属性
   List onClasses = this.getCandidates(metadata, ConditionalOnClass.class);
   List onMissingClasses;
   if(onClasses != null) {
       // 找出不在类路径中的类
       onMissingClasses = this.getMatches(onClasses, OnClassCondition.MatchType.MISSING, classLoader);
       // 如果存在不在类路径中的类,匹配失败
       if(!onMissingClasses.isEmpty()) {
           return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class, new Object[0]).didNotFind("required class", "required classes").items(Style.QUOTE, onMissingClasses));
       }
       matchMessage = matchMessage.andCondition(ConditionalOnClass.class, new Object[0]).found("required class", "required classes").items(Style.QUOTE, this.getMatches(onClasses, OnClassCondition.MatchType.PRESENT, classLoader));
   }
   // 接着找出所有ConditionalOnMissingClass注解的属性
   // 它与ConditionalOnClass注解的含义正好相反,所以以下逻辑也与上面相反
   onMissingClasses = this.getCandidates(metadata, ConditionalOnMissingClass.class);
   if(onMissingClasses != null) {
       List present = this.getMatches(onMissingClasses, OnClassCondition.MatchType.PRESENT, classLoader);
       if(!present.isEmpty()) {
           return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingClass.class, new Object[0]).found("unwanted class", "unwanted classes").items(Style.QUOTE, present));
       }
       matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class, new Object[0]).didNotFind("unwanted class", "unwanted classes").items(Style.QUOTE, this.getMatches(onMissingClasses, OnClassCondition.MatchType.MISSING, classLoader));
   }
   return ConditionOutcome.match(matchMessage);
}
// 获得所有annotationType注解的属性
private List<String> getCandidates(AnnotatedTypeMetadata metadata, Class<?> annotationType) {
   MultiValueMap attributes = metadata.getAllAnnotationAttributes(annotationType.getName(), true);
   ArrayList candidates = new ArrayList();
   if(attributes == null) {
       return Collections.emptyList();
   } else {
       this.addAll(candidates, (List)attributes.get("value"));
       this.addAll(candidates, (List)attributes.get("name"));
       return candidates;
   }
}
private void addAll(List<String> list, List<Object> itemsToAdd) {
   if(itemsToAdd != null) {
       Iterator var3 = itemsToAdd.iterator();
       while(var3.hasNext()) {
           Object item = var3.next();
           Collections.addAll(list, (String[])((String[])item));
       }
   }
}    
// 根据matchType.matches方法来进行匹配
private List<String> getMatches(Collection<String> candidates, OnClassCondition.MatchType matchType, ClassLoader classLoader) {
   ArrayList matches = new ArrayList(candidates.size());
   Iterator var5 = candidates.iterator();
   while(var5.hasNext()) {
       String candidate = (String)var5.next();
       if(matchType.matches(candidate, classLoader)) {
           matches.add(candidate);
       }
   }
   return matches;
}

关于match的具体实现在MatchType中,它是一个枚举类,提供了PRESENT和MISSING两种实现,前者返回类路径中是否存在该类,后者相反。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
private static enum MatchType {
   PRESENT {
       public boolean matches(String className, ClassLoader classLoader) {
           return OnClassCondition.MatchType.isPresent(className, classLoader);
       }
   },
   MISSING {
       public boolean matches(String className, ClassLoader classLoader) {
           return !OnClassCondition.MatchType.isPresent(className, classLoader);
       }
   };
   private MatchType() {
   }
   // 跟我们之前看过的案例一样,都利用了类加载功能来进行判断
   private static boolean isPresent(String className, ClassLoader classLoader) {
       if(classLoader == null) {
           classLoader = ClassUtils.getDefaultClassLoader();
       }
       try {
           forName(className, classLoader);
           return true;
       } catch (Throwable var3) {
           return false;
       }
   }
   private static Class<?> forName(String className, ClassLoader classLoader) throws ClassNotFoundException {
       return classLoader != null?classLoader.loadClass(className):Class.forName(className);
   }
   public abstract boolean matches(String var1, ClassLoader var2);
}

现在终于真相大白,@ConditionalOnClass的含义是指定的类必须存在于类路径下,MongoDataAutoConfiguration类中声明了类路径下必须含有Mongo.class, MongoTemplate.class这两个类,否则该自动配置类不会被加载。

在Spring Boot中到处都有类似的注解,像@ConditionalOnBean(容器中是否有指定的Bean),@ConditionalOnWebApplication(当前工程是否为一个Web工程)等等,它们都只是@Conditional注解的扩展。当你揭开神秘的面纱,去探索本质时,发现其实Spring Boot自动配置的原理就是如此简单,在了解这些知识后,你完全可以自己去实现自定义的自动配置类,然后编写出自定义的starter。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-07-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码农沉思录 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
手把手教你安装黑苹果之openCore-0.6.3 EFI制作全过程,非常详细
这篇文章主要是记录自己动手安装Big Sur在过程,和心理。略显繁琐,请自行跳跃观看。
全栈程序员站长
2022/09/12
22.7K0
手把手教你安装黑苹果之openCore-0.6.3 EFI制作全过程,非常详细
史上最全的黑苹果系统「MacOS」安装教程,小白也能秒掌握!
折腾过的人应该不陌生,自从苹果采用 Intel 的处理器,被解锁后可以安装在 Intel CPU 与部分 AMD CPU 的机器上。从而出现了一大批非苹果设备而使用苹果操作系统的机器,被称为黑苹果(Hackintosh)。
全栈程序员站长
2022/07/01
14.9K0
史上最全的黑苹果系统「MacOS」安装教程,小白也能秒掌握!
黑苹果扯犊子篇
近期发布了利用的checkm8漏洞的越狱工具,兼容的设备A7-A11(iPhone 5S~iPhone X)的12.3和以上系统,需要macOS安装软件(官网:https://checkra.in)支持白苹果,黑苹果,据说不支持虚拟机,越狱的教程 我这里就不再复制粘贴了,可以看看别的地方的文章
zby1101
2020/08/05
1.9K0
黑苹果扯犊子篇
【Share】Dell Precision 5510 Mojave Clover分享
首先先感谢 @darkhandz @黑果小兵 @Scottsanett 等大佬的分享
Hyejeong小DD
2018/12/04
5.7K1
【Share】Dell Precision 5510 Mojave Clover分享
Clover引导简明教程
选择 Boot macOS with selected options 启动 出现错误画面拍照发群里寻求帮助。
慕白
2020/01/02
17.3K1
Clover引导简明教程
黑苹果安装手记(一)
自从苹果的电脑采用了Intel的处理器,苹果的系统被黑客破解之后,能安装在Intel CPU与部分AMD CPU上,从而就出现了一大批非苹果电脑的设备,而使用苹果操作系统的机器。这一类就被称为黑苹果(Hackintosh)。简单的说,就是在非苹果电脑上,安装的苹果系统。
简单并不简单
2019/12/17
4.2K0
黑苹果安装手记(一)
技嘉AMD AX370 Gaming K3黑苹果Opencore引导EFI
其实黑苹果对于 reizhi 来说并不是刚需生产力工具,也不算是装逼好玩,只不过是某种情怀使然。想起来很多年前在 AMD 速龙2上折腾黑苹果的经历,不禁让人感叹 Clover 时代黑苹果的门槛降低了很多(当然也离不开各路大神对于驱动的贡献)。虽然目前 AMD Ryzen 平台使用 Clover 引导也还好好的,不过并不支持 macOS 10.15.2 及以上。所以只好还是向 Opencore 寻求解决方案。不得不说 Opencore 目前处在起步阶段,配置起来要比 Clover 麻烦得多。
reizhi
2022/09/26
1.3K0
技嘉AMD AX370 Gaming K3黑苹果Opencore引导EFI
杂项-黑苹果安装教程「建议收藏」
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/138553.html原文链接:https://javaforall.cn
全栈程序员站长
2022/08/23
5.1K0
黑苹果安装手记(二)
小编也是小白,现学现卖,现在仅能到把自己电脑的驱动都完善了,于是小编也写一下自己安装的过程,希望能让像我一样的小白同学也能装上黑苹果。
简单并不简单
2019/12/20
2.5K0
浅谈 Mac 黑苹果 Hackintosh 安装使用
这次我们聊下 MacOS,因为最近给笔记本(intel/nvidia)和台式机(amd/ati)吃上了黑苹果,也就是用上了 Mac OS 苹果电脑系统。很久以前就想过搞个 mac 玩一下,那时候没那个精力去搞事(其实还是懒)简单弄了个虚拟机苹果玩了下,体验极差!后来一想干脆算了,可能最后苹果吃不成还把现有系统搭进去都有可能hhh?.. 所以后面一直没搞过,win10随着时间的迭代也逐渐完善起来之后就更没有上苹果的想法了嗯。
2Broear
2024/03/12
3090
浅谈 Mac 黑苹果 Hackintosh 安装使用
HP暗影精灵3黑苹果基本完工
闲暇之余,又一次给暗影精灵3,装上了黑苹果(MacOS 10.14.5)。实现完美电源管理,以及不插电开机(暗影精灵系列的朋友,装过黑苹果的应该知道意味着什么)。并将efi以及补丁发布出来,以便相同的笔记本可以安装。
Bess Croft
2020/04/03
4.4K2
完美黑苹果功能自检手册
很多朋友自己鼓捣完黑苹果或者花钱请被人帮忙安装好黑苹果后,并不清楚目前自己的黑苹果完美度是多少。因此分享一下我心目中完美的黑苹果各项功能自检列表,看看您的黑苹果完美度有多少。
轩辕镜像
2024/09/29
2K0
完美黑苹果功能自检手册
OpenCore引导黑苹果
OpenCore(OC)是一种新的引导方式,随着越来越多的kexts开始放弃Clover, 我相信提早使用OC会对你未来使用黑苹果会有很大的帮助。这是一个自然的现象,就像变色龙被Clover淘汰,而现在OC代替Clover也是大势所趋。你应该需要看一些相关的文章,来帮助你理解我的正文内容,同时也需要下载我推荐的软件:
用户6808043
2022/02/25
2.1K0
安装CLOVER引导器到硬盘EFI分区
彻底脱离CLOVER引导U盘 目录: 1使用EFI TOOLS Clover 安装CLOVER引导器到EFI分区。 2使用Clover v2.3k rXXXX.pkg 安装CLOVER引导器到EFI分区 前言 我们的电脑里已经安装好了双系统,但是之前都是通过启动CLOVER引导U盘进行引导双系统的。 本章节内容,将简单的介绍将在MAC系统(=OSX系统)下将CLOVER引导器安装到硬盘EFI分区。至于WIN系统下,由于过程比较繁琐,再加上没有太多的必要性。因此本章节只讲解在MAC系统下。
全栈程序员站长
2022/07/23
5.6K0
安装CLOVER引导器到硬盘EFI分区
黑苹果,你准备好了吗
黑苹果、是把苹果公司出品的macOS操作系统在x86架构的非苹果电脑上运行的黑客协作计划。此计划的构思始于2005年6月的苹果全球开发者大会(WWDC 2005),当时苹果宣布他们将把其个人电脑从PowerPC架构转向英特尔架构。
海哥@开发
2022/04/06
1.3K0
黑苹果,你准备好了吗
联想Z470黑化之路:硬件升级还能刷苹果Mac系统!
11年入手了一台联想Z470,到现在也有些年头了,当年是看中了它的外观,现在想来性能是它的短板。然而为了工作需要,我便又购置了一台高性能电脑。现如今便想着怎么处理这台小Z,有人建议当废品出售,但无论如何它都跟了我这么多年,舍弃有些不忍。抱着勤俭持家的态度,我便狠了狠心决定多花点钱,将它全面更新升级。在上网找了些资料后,便开始整理思路,汇总如下: 更新内容:将原有部分硬件换新(声卡、网卡、外壳、键盘等) 升级内容:内存加到8G,添加固态硬盘 系统更换:黑化之苹果系统 这其中最繁琐的要数装黑苹果系统,技术含量
FB客服
2018/02/28
2.7K0
联想Z470黑化之路:硬件升级还能刷苹果Mac系统!
OC简要配置说明(旧)已修正
注意事项:OC对于有依赖的SSDT/KEXT加载顺序有严格要求,注意在config配置中的顺序。 主要适用于UEFI启动的电脑。 本文当前写作时OC正式版为0.5.9,0.6.0测试版。以下的配置适用于这两个版本,后续OC的更新可能会有些许改动,到时候应该再参考官方文档进行修改。
GOOPHER
2022/03/31
8.5K0
OC简要配置说明(旧)已修正
黑苹果安装教程OC引导「建议收藏」
首先声明,我也是小白,只是总结一下我安装黑苹果过程中参考过的教程。 以下内容如有帮助本人深感欣慰。
全栈程序员站长
2022/06/28
15.2K0
黑苹果安装教程OC引导「建议收藏」
黑苹果完整安装教程,内含后续系统优化「建议收藏」
这类主讲装双系统,VM虚拟机参考博客https://www.jianshu.com/p/5f10473f9047 虚拟机下载:https://www.vmware.com/go/getworkstation-win 秘钥:YG5H2-ANZ0H-M8ERY-TXZZZ-YKRV
全栈程序员站长
2022/08/28
7.9K0
黑苹果完整安装教程,内含后续系统优化「建议收藏」
记一次黑苹果的安装
最近老高的MBP和MACmini卡的不行,想换硬件吧,硬件直接焊死,简直良心苹果,参考了很多黑苹果的安装贴后果断决定在我的台式机上安装最新版的macOS-High-Sierra-10.13.6,系统选择的是【黑果小兵】,确实好用,老高十分推荐!
老高的技术博客
2022/12/28
2.1K0
记一次黑苹果的安装
推荐阅读
相关推荐
手把手教你安装黑苹果之openCore-0.6.3 EFI制作全过程,非常详细
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档