Spring使用——@Profile使用

配置類

package com.ysy.config;

import com.ysy.bean.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * @author shanyangyang
 * @date 2020/6/8
 *  * Profile:指定組件在哪個環境的情況下從能被註冊到容器中;不指定,任何環境下都能註冊到容器中
 *  * 		spring爲我們提供的可以根據當前環境,動態的激活和切換一系列組件的功能
 *  * 	開發環境、測試環境和生產環境
 *  * 	數據源:A、B、C
 *
 *  寫在配置類上,只有是指定的環境,整個配置類中的Bean纔會注入;否則包括配置類在內都不會註冊;
 *
 *  沒有標註@Profile註解的類,在任何環境下都會加載
 */
@Profile("testB")
@Configuration
public class MainConfigOfProfile {

	@Profile("testA")
	@Bean
	public DataSource dataSourceA(){
		DataSource dataSource = new DataSource();
		dataSource.setUser("A");
		dataSource.setPasswd("1");
		return dataSource;
	}

	@Profile("devB")
	@Bean
	public DataSource dataSourceB(){
		DataSource dataSource = new DataSource();
		dataSource.setUser("A");
		dataSource.setPasswd("1");
		return dataSource;
	}

	@Profile("proC")
	@Bean
	public DataSource dataSourceC(){
		DataSource dataSource = new DataSource();
		dataSource.setUser("A");
		dataSource.setPasswd("1");
		return dataSource;
	}
}

測試類

package com.ysy.test;

import com.ysy.config.MainConfigOfProfile;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author shanyangyang
 * @date 2020/6/8

 */
public class IOCTestOfProfile {
	//AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfProfile.class);

	//1、使用命令行動態參數,在虛擬機參數位置加載:-Dspring.profiles.active=test
	//2、創建一個AnnotationConfigApplicationContext對象,無參構造器;設置需要激活的環境;註冊配置類,啓動刷新容器
	@Test
	public void test01(){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.getEnvironment().setActiveProfiles("testA");
		context.register(MainConfigOfProfile.class);
		context.refresh();
		print(context);
	}

	private void print(AnnotationConfigApplicationContext context) {
		String[] beanDefinitionNames = context.getBeanDefinitionNames();
		for (String name:beanDefinitionNames){
			System.out.println(name);
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章