1. 程式人生 > >spring profile選擇不同資料來源

spring profile選擇不同資料來源

spring profile提供了一種方法,用於解決專案在不同環境中自動選擇不同的配置。

package com.spring.di;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * 根據環境不同選擇不同的配置
 * 
 * @author  
 * @time    2018年9月5日
 * @e-mail  
 * @company 
 */

@Configuration
public class ProfileConfig {
	
	@Bean
	@Profile(value="dev")
	public DataSoruce dev(){
		return new DataSoruce("dev");
	}
	
	@Bean
	@Profile(value="test")
	public DataSoruce test(){
		return new DataSoruce("test");
	}
	
	@Bean
	@Profile(value="pro")
	public DataSoruce pro(){
		return new DataSoruce("pro");
	}
}

@Configuration
class DataSoruce{
	private String name;
	
	public DataSoruce(String name) {
		this.name = name;
	}

	public final String getName() {
		return name;
	}

	public final void setName(String name) {
		this.name = name;
	}
	
}

上面程式碼中,我們定義一個數據源物件,(實際中的資料來源當然不是這樣的,嘻嘻)。我們使用spring profile提供的@Profile註解宣告不同的資料來源。這樣我們就為不同的資料來源建立了不同的bean。下面我們利用spring提供的@ActiveProfiles註解來測試。

package com.spring.di;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ProfileConfig.class)
@ActiveProfiles(value="pro")
public class ProfileConfigTest {
	
	@Autowired
	private DataSoruce dataSource;
	
	@Test
	public void test(){
		System.out.println(dataSource.getName());
	}
}

執行結果

con

說明我們成功激活了pro(生產環境的配置源)!