spring注解开发——@Profile根据环境动态注册组件

根据环境动态激活组件☞@Profile

我们一般会有这样的需求,开发环境用的数据源与生产环境不一样,也就是dev环境我们想要使用dev的DataSource,生产的我们使用生产的DataSource,此时我们就要用到@Profile注解。

我们看下面的案例:配置文件有三个bean,我们想在不同环境只激活其中的一个

@Configuration
public class ProfileAnnotationContextConfig {

    @Profile("dev")
    @Bean
    public ColorYellow colorYellow() {
        return new ColorYellow();
    }

    @Profile("pro")
    @Bean
    public ColorWhite colorWhite() {
        return new ColorWhite();
    }

    @Profile("default")
    @Bean
    public ColorRed colorRed() {
        return new ColorRed();
    }
}

激活特定环境,我们可以这么做:

@Test
    public void testProfileAnnotation() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.getEnvironment().setActiveProfiles("dev");
        applicationContext.register(ProfileAnnotationContextConfig.class);
        applicationContext.refresh();

    }

这里我们激活了dev环境,那么@Profile为dev的组件将被注册到容器。如果我们没有激活任何环境,大家可以看到我的第三个bean,@Profile(“default”),此时标注为default的组件将被注册到容器。

题外话,我们平时创建容器的时候都是这样的:

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ProfileAnnotationContextConfig.class);

直接用的AnnotationConfigApplicationContext类的有参构造函数,这里我们为了在创建容器之前设置一些参数,比如这里的激活哪个环境,所以用了无参,但是为啥还有下面的两步applicationContext.register(),applicationContext.refresh()呢,这个我们要来看看用有参构造器时spring为我们干了啥:

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		this();
		register(annotatedClasses);
		refresh();
	}

可以看到,其实构造容器时spring也分了三步:①调用无参构造器创建对象,②注册组件,③刷新容器。

以上是@Profile注解的相关内容,深入研究靠自己了~

猜你喜欢

转载自blog.csdn.net/chenshufeng115/article/details/100139445
今日推荐