美文网首页
环境与 profile和条件化的 bean

环境与 profile和条件化的 bean

作者: 禅与发现的乐趣 | 来源:发表于2018-07-05 16:35 被阅读17次

环境与 profile

在开发软件的时候,需要从一个环境迁移到另一个环境,相应的很多配置都会改变,比如数据库源,开发、测试和生产环境是完全不一样的,在不同的环境,对应不同的配置文件进行重新构建可能会引入 bug,庆幸的是,Spring 提供的解决方案并不需要重新构建。

配置 profile bean

要使用 profile,首先要将所有不同的 bean 定义整理到一个或多个 profile 之中,在将应用部署到每个环境时,要确保对应的 profile 处于激活状态。

在 Java 配置中,可以使用注解@Profile指定某个 bean 属于哪一个 profile。

@Configuration
@Profile("dev")
public class DevelopmentProdileConfig {

    @Bean()
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:schema.sql")
                .addScript("classpath:test-data.sql")
                .build();
    }
}

上面代码的@Profile注解应用在了类级别上,它会告诉 Spring 这个配置类中的 bean 只有在 dev profile 激活时才会创建。如果没有激活的话,那么带有@Bean注解的方法都会被忽略。

同样,生产环境的配置可能如下所示:

@Configuration
@Profile("prod")
public class ProductionProfileConfig {

    @Bean
    public DataSource dataSource() {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
        bean.setJndiName("jdbc/myDS");
        bean.setResourceRef(true);
        bean.setProxyInterface(javax.sql.DataSource.class);
        return (DataSource) bean.getObject();
    }
}

在 Spring3.1中,只能在类级别上使用@Profile注解,不过,从 Spring3.2开始,也可以在方法级别上使用@Profile注解了。

@Configuration
public class DataSourceConfig {

    @Bean()
    @Profile("dev")
    public DataSource embeddedDataSource() {
        return (DataSource) new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:schema.sql")
                .addScript("classpath:test-data.sql")
                .build();
    }

    @Bean
    @Profile("prod")
    public DataSource jndiDataSource() {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
        bean.setJndiName("jdbc/myDS");
        bean.setResourceRef(true);
        bean.setProxyInterface(javax.sql.DataSource.class);
        return (DataSource) bean.getObject();
    }
}

需要注意的是,没有指定 profile 的 bean 始终都会被创建,与激活哪个 profile 没有关系。

在 XML 中配置 profile
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/jdbc
       http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd"
       profile="dev">

    <jdbc:embedded-database id="dataSource">
        <jdbc:script location="classpath:schema.sql" />
        <jdbc:script location="classpath:test-data.sql" />
    </jdbc:embedded-database>

</beans>

还可以对应着做如下配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="http://www.springframework.org/schema/jdbc
       http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">

    <beans profile="dev">
        <jdbc:embedded-database id="dataSource">
            <jdbc:script location="classpath:schema.sql" />
            <jdbc:script location="classpath:test-data.sql" />
        </jdbc:embedded-database>
    </beans>

    <beans profile="prod" >
        <jee:jndi-lookup id="dataSource"
                         jndi-name="jdbc/MyDatabase"
                         resource-ref="true"
                         proxy-interface="javax.sql.DataSource" />
    </beans>
</beans>
激活profile

Spring 在确定哪个 profile 处于激活状态时,需要依赖两个独立的属性:spring.profiles.activespring.profiles.default。如果设置了 active 属性的话,那么它的值就会用来确定那个 profile 是激活的。但是如果没有设置 active 属性的话,Spring 将会查找 default 属性,如果都没有设置的话,就没有激活的 profile,就只会创建那么没有定义在 profile 中的 bean。

有多种方法可以设置这两个属性:

  • 作为 DispatcherServlet 的初始化参数

  • 作为 Web 应用的上下文参数

  • 作为 JNDI 条目

  • 作为环境变量

  • 作为 JVM 的系统属性

  • 在集成测试类上,使用@ActiveProfiles 注解设置。

条件化的 bean

有时候,你可能希望一个或多个 bean 只有在应用的类路径下包含特定的库时才创建,或者希望某个 bean 只有当另外某个特定的 bean 也声明了之后才创建,还可能要求只有某个特定的环境变量设置之后,才会创建某个 bean。

要实现条件化的 bean使用 Spring4之后引入的@Conditional注解即可,我们先通过一个例子展开:

@Bean
@Conditional(MagicExistsCondition.class)
public MagicBean magicBean() {
    return new MagicBean();
}

上面的一个简单的 bean 添加了@Conditional注解,指定了一个条件类。设置给@Conditional的类可以是任意实现了 Condition 接口的类型:

public class MagicExistsCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        return false;
    }
}

这个类的实现可以说是相当简单了,只要在 matches 中做好判断,返回 true 或 false 即可。

上面的条件为,判断环境中是否存在 magic 属性:

public class MagicExistsCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Environment environment = conditionContext.getEnvironment();
        return environment.containsProperty("magic");
    }
}

所以可以知道,bean 的条件有多强大,取决于 matches 中两个参数的功能。

public interface ConditionContext {
    BeanDefinitionRegistry getRegistry();

    ConfigurableListableBeanFactory getBeanFactory();

    Environment getEnvironment();

    ResourceLoader getResourceLoader();

    ClassLoader getClassLoader();
}
  • BeanDefinitionRegistry getRegistry() 检查 bean 的定义

  • ConfigurableListableBeanFactory getBeanFactory() 检查 bean 是否存在,探测 bean 的属性

  • Environment getEnvironment() 检查环境变量是否存在以及它的值是什么

  • ResourceLoader getResourceLoader() 读取并探查加载的资源

  • ClassLoader getClassLoader() 加载并检测类是否存在

AnnotatedTypeMetadata能让我们检查带有@Bean 注解的方法上还有什么其它的注解。

public interface AnnotatedTypeMetadata {
    boolean isAnnotated(String var1);

    Map<String, Object> getAnnotationAttributes(String var1);

    Map<String, Object> getAnnotationAttributes(String var1, boolean var2);

    MultiValueMap<String, Object> getAllAnnotationAttributes(String var1);

    MultiValueMap<String, Object> getAllAnnotationAttributes(String var1, boolean var2);
}

Spring4后,Spring 对 Profile 进行了重构,使用了 Conditional 注解,正好用来学习学习:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({ProfileCondition.class})
public @interface Profile {
    String[] value();
}

我们来看看 ProfileCondition 的条件:

class ProfileCondition implements Condition {
    ProfileCondition() {
    }

    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        if (context.getEnvironment() != null) {
            MultiValueMap<String, Object> 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;
    }
}

matches 中判断了 profile 是否处于激活状态。

相关文章

网友评论

      本文标题:环境与 profile和条件化的 bean

      本文链接:https://www.haomeiwen.com/subject/bjbpuftx.html