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(生产环境的配置源)!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值