【SpringBoot】AutoConfiguration 解密

来源:互联网 发布:杀毒清理软件 编辑:程序博客网 时间:2024/05/17 06:48

我们知道SpringBoot的应用可以以非常简洁的代码去做很多的事情, 可以自动帮你注入数据库的Bean,消息队列的Bean等等等等,那么SpringBoot是怎么做到的呢?

但是在探索SpringBoot的神秘之前,我们先了解一下Spring的 @Conditional 注解,这是SpringBoot的 AutoConfiguration 的神奇之处所依赖的底层机制。

@Conditional 探秘

我们开发Spring应用的时候有时候会碰到要 根据外界条件注册不同Bean 的情况。

比如如果你的应用是跑在本地机器的话,你会想要让你的 DataSource bean指向一个本地的数据库,而如果是跑在线上机器的话,你会想让 DataSource bean指向一个生产的数据库。

你可以把这些数据库连接信息抽取到几个不同的配置文件里面去,然后在不同的环境下使用不同的配置文件。但是当你的应用被部署到新的环境下的时候,你还是要添加新的配置文件,并且重新打包。( 译者注:这里其实只要把配置文件抽取到代码之外不就好了么?不知道原作者在想什么 )

为了解决这个问题,Spring 3.1引入了 Profiles 的概念。你可以注册同一个类型bean的不同实例,然后把这些不同的实例绑定到不同的 Profile , 当你运行这个Spring应用的时候,你可以指定你要激活的 Profile , 这样只有跟这些被激活的 Profile 相关联的bean才会被注册:

@Configurationpublic class AppConfig{    @Bean    @Profile("DEV")    public DataSource devDataSource() {        ...    }    @Bean    @Profile("PROD")    public DataSource prodDataSource() {        ...    }}

然后你可以通过系统属性指定激活的profile:

-Dspring.profiles.active=DEV

这种方式对于你要基于profile来决定是否注册一个bean的情况工作得很好。但是如果你要基于一些条件性的判断逻辑来决定是否注册一个bean的话,那么光靠profile是不行的。

为了给条件性地注册bean提供更高的灵活性,Spring 4提供了 @Conditional 的概念。通过使用 @Conditional 你可以基于任何条件来决定是否注册一个bean。

你的 条件 可能是这样的:

  • CLASSPATH里面有一个特定的Class
  • ApplicationContext里面有一个特定类型的bean
  • 在指定的位置有指定的文件
  • 配置文件里面有指定的配置项
  • 系统属性里面配置了指定的属性

这些只是我能想到的一些,实际上你可以基于 任何 条件。下面让我们来看看Spring的 @Conditional 到底是如何工作的。我们先设定一个场景:

我们有一个 UserDAO 接口用来从数据库里面获取数据。这个接口我们有两个实现: JdbcUserDAO 从 MySQL 数据库里面获取数据; MongoUserDAO 从 MongoDB 里面获取数据。

通过系统属性来决定

我们想通过一个名为 dbType 的系统属性来决定到底使用 JdbcUserDAO 还是 MongoUserDAO 。期望的效果是,如果通过 java -jar myapp.jar -DdbType=MySQL 那么使用的是 JdbcUserDAO , 如果通过 java -jar myapp.jar -DdbType=MONGO 启动,这使用 MongoUserDAO 。几个类的实现是这样的:

public interface UserDAO{    List<String> getAllUserNames();}public class JdbcUserDAO implements UserDAO{    @Override    public List<String> getAllUserNames()    {        System.out.println("**** Getting usernames from RDBMS *****");        return Arrays.asList("Siva","Prasad","Reddy");    }}public class MongoUserDAO implements UserDAO{    @Override    public List<String> getAllUserNames()    {        System.out.println("**** Getting usernames from MongoDB *****");        return Arrays.asList("Bond","James","Bond");    }}

我们可以实现这样的一个 MySQLDatabaseTypeCondition 来检测系统属性 dbType 是否是 MYSQL :

public class MySQLDatabaseTypeCondition implements Condition{    @Override    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata)    {        String enabledDBType = System.getProperty("dbType");        return (enabledDBType != null && enabledDBType.equalsIgnoreCase("MYSQL"));    }}

类似的 MongoDBDatabaseTypeCondition :

public class MongoDBDatabaseTypeCondition implements Condition{    @Override    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata)    {        String enabledDBType = System.getProperty("dbType");        return (enabledDBType != null && enabledDBType.equalsIgnoreCase("MONGODB"));    }}

现在我们就可以通过 @Conditional 来判断使用 JdbcUserDAO 还是 MongoUserDAO :

@Configurationpublic class AppConfig{    @Bean    @Conditional(MySQLDatabaseTypeCondition.class)    public UserDAO jdbcUserDAO(){        return new JdbcUserDAO();    }    @Bean    @Conditional(MongoDBDatabaseTypeCondition.class)    public UserDAO mongoUserDAO(){        return new MongoUserDAO();    }}

通过CLASSPATH上是否有指定的类来判断

类似地我们可以通过判断CLASSPATH里面是否有 com.mongodb.Server 这个Driver类来决定是使用 MongoUserDAO 还是 JdbcUserDAO :

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;        }    }}

通过容器里面是否存在指定类型bean来判断

如果我们只在容器里面没有任何类型的 UserDAO 的bean的时候才注册 MongoUserDAO 。我们通过创建一个Condition来检测是否存在一个指定类型的bean:

public class UserDAOBeanNotPresentsCondition implements Condition{    @Override    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata)    {        UserDAO userDAO = conditionContext.getBeanFactory().getBean(UserDAO.class);        return (userDAO == null);    }}

如果想通过配置文件里面的配置来决定DAO类型呢?

public class MongoDbTypePropertyCondition implements Condition{    @Override    public boolean matches(ConditionContext conditionContext,    AnnotatedTypeMetadata metadata)    {        String dbType = conditionContext.getEnvironment()                            .getProperty("app.dbType");        return "MONGO".equalsIgnoreCase(dbType);    }}

更优雅的实现方式: 注解

我们已经试了通过各种不同条件来实现 Condition 。但是其实有更优雅的、通过注解来实现Condition的方式。我们不再为 MYSQL 和 MongoDB 实现各自 Condition , 我们可以实现下面这样一个 DatabaseType 注解:

@Target({ ElementType.TYPE, ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)@Conditional(DatabaseTypeCondition.class)public @interface DatabaseType{    String value();}

然后我们实现 DatabaseTypeCondition 来使用这个注解来判断DAO的类型了:

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");        String enabledDBType = System.getProperty("dbType","MYSQL");        return (enabledDBType != null && type != null && enabledDBType.equalsIgnoreCase(type));    }}

现在我们就可以在我们的bean上使用 DatabaseType 注解了:

@Configuration@ComponentScanpublic class AppConfig{    @Bean    @DatabaseType("MYSQL")    public UserDAO jdbcUserDAO(){        return new JdbcUserDAO();    }    @Bean    @DatabaseType("MONGO")    public UserDAO mongoUserDAO(){        return new MongoUserDAO();    }}

这里我们从 DatabaseType 注解里面获取元数据,并且把获取的值跟系统属性里面的 dbType 进行对比来决定是否激活bean。

我们已经看了很多例子来看 @Conditional 注解的作用。SpringBoot大量的使用 @Conditional 来实现基于条件的注册bean。你可以在 spring-boot-autoconfigure-{version}.jar 的 org.springframework.boot.autoconfigure 包里面看到SpringBoot使用的大量的 Condition 的实现。

那么我们已经知道了SpringBoot使用 @Conditional 来决定是否初始化一个bean, 但是是什么机制触发了 auto-configuration 机制呢? 我们下一节来聊聊这个事情:

SprintBoot的自动配置

SpringBoot的自动配置的关键在于 @EnableAutoConfiguration 这个注解。一般来说我们把我们程序的入口类加上 @SpringBootApplication 注解,或者如果我们想要更加细致的定制这些默认值的话:

@Configuration@EnableAutoConfiguration@ComponentScanpublic class Application{}

@EnableAutoConfiguration 注解通过扫描CLASSPATH里面所有的组件,然后基于条件来决定是否注册bean来使得Spring的ApplicationContext自动配置。

SpringBoot在 spring-boot-autoconfigure-{version}.jar 里面提供了很多 AutoConfiguration 的类来负责注册各种不同的组件。

一般来说 AutoConfiguration 类上面会标上 @Configuration 注解来标明它是一个Spring的配置类,标上 @EnableConfigurationProperties 来绑定自定义的配置值,并且会在一到多个方法上标上 @Conditional 注解来标记注册方法。

比如我们来看看 org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration :

@Configuration@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })@EnableConfigurationProperties(DataSourceProperties.class)@Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class })public class DataSourceAutoConfiguration{    ...    ...    @Conditional(DataSourceAutoConfiguration.EmbeddedDataSourceCondition.class)    @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })    @Import(EmbeddedDataSourceConfiguration.class)    protected static class EmbeddedConfiguration {    }    @Configuration    @ConditionalOnMissingBean(DataSourceInitializer.class)    protected static class DataSourceInitializerConfiguration {        @Bean        public DataSourceInitializer dataSourceInitializer() {        return new DataSourceInitializer();        }    }    @Conditional(DataSourceAutoConfiguration.NonEmbeddedDataSourceCondition.class)    @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })    protected static class NonEmbeddedConfiguration {        @Autowired        private DataSourceProperties properties;        @Bean        @ConfigurationProperties(prefix = DataSourceProperties.PREFIX)        public DataSource dataSource() {            DataSourceBuilder factory = DataSourceBuilder                    .create(this.properties.getClassLoader())                    .driverClassName(this.properties.getDriverClassName())                    .url(this.properties.getUrl()).username(this.properties.getUsername())                    .password(this.properties.getPassword());            if (this.properties.getType() != null) {                factory.type(this.properties.getType());            }            return factory.build();        }    }    ...    ...    @Configuration    @ConditionalOnProperty(prefix = "spring.datasource", name = "jmx-enabled")    @ConditionalOnClass(name = "org.apache.tomcat.jdbc.pool.DataSourceProxy")    @Conditional(DataSourceAutoConfiguration.DataSourceAvailableCondition.class)    @ConditionalOnMissingBean(name = "dataSourceMBean")    protected static class TomcatDataSourceJmxConfiguration {        @Bean        public Object dataSourceMBean(DataSource dataSource) {        ....        ....        }    }    ...    ...}

这里 DataSourceAutoConfiguration 上标记了一个 @ConditionalOnClass({ DataSource.class,EmbeddedDatabaseType.class }) , 这样只有当CLASSPATH上有 DataSource.class 和 EmbeddedDatabaseType.class 的时候, DataSourceAutoConfiguration 才会生效。

这个类还被 @EnableConfigurationProperties(DataSourceProperties.class) 标记了,这样 application.properties 里面相关的配置值会自动绑定到 DataSourceProperties 上面。

@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)public class DataSourceProperties implements BeanClassLoaderAware, EnvironmentAware, InitializingBean {    public static final String PREFIX = "spring.datasource";    ...    ...    private String driverClassName;    private String url;    private String username;    private String password;    ...    //setters and getters}

有了这个配置属性类,所有 spring.datasource.* 的配置都会自动绑定到 DataSourceProperties :

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=secretspring.datasource.driver-class-name=com.mysql.jdbc.Driver

你还能看到一些内部类以及bean的定义方法被SpringBoot的 @ConditionalOnMissingBean , @ConditionOnClass , @ConditionalOnProperty 等等标记。

这些bean的定义只有在那些条件满足的时候才会注册。

在 spring-boot-autoconfigure-{version}.jar 里面你还能看到其它的 AutoConfiguration 类:

  • org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration
  • org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
  • org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
  • org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration

等等。我希望通过今天文章的介绍大家已经理解SpringBoot是怎么做到自动配置bean的了。

0 0