spring-@Profile源码跟踪

@Profile标签可以让你在不同的环境切换bean。


@Profile也是一个条件化配置,因此,一个被@Profile注解的bean最后是能否注册到上下文由ProfileCondition.class决定。

package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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


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());//获取当前被@Profile注解的@Profile的value值。
            if(attrs != null) {
                Iterator var4 = ((List)attrs.get("value")).iterator();

                Object value;
                do {
                    if(!var4.hasNext()) {//如果最后都没有找到对应的值,返回false,不需要注册当前被@Profile注解的bean
                        return false;
                    }

                    value = var4.next();//下一个bean
                } while(!context.getEnvironment().acceptsProfiles((String[])((String[])value)));//@Profile的值是否符合当前环境,是的话跳出循环
												//不是的话继续next。

                return true;//注册当前bean
            }
        }

        return true;
    }
}


public interface DatabaseConfig {

    DataSource createDataSource();

}

开发环境配置

@Configuration
@Profile(value = "dev")
public class DevDatabaseConfig implements DatabaseConfig{

    @Bean
    public DataSource createDataSource() {
        System.out.println("create dev database..");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        return dataSource;
    }

}

线上环境配置

@Configuration
@Profile(value = "pro")
public class ProductionDatabaseConfig implements DatabaseConfig {

    @Bean
    public DataSource createDataSource() {

        System.out.println("create pro database");
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        return dataSource;
    }

}

测试代码

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.getEnvironment().setActiveProfiles("pro");//设置环境
        context.scan("com.*");
        context.refresh();
        context.close();



调试

DevDatabaseConfig




ProductionDatabaseConfig




输出

org.springframework.core.type.classreading.MethodMetadataReadingVisitor
create pro database


设置了@Profile之后需要激活,激活访问有好几种,比如jvm,spring设置等等。

参考

http://blog.csdn.net/hj7jay/article/details/53634159

https://www.cnblogs.com/chenpi/p/6213849.html

https://www.cnblogs.com/jeffen/p/6136371.html


猜你喜欢

转载自blog.csdn.net/helianus/article/details/78772470