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());
}
}
运行结果
说明我们成功激活了pro(生产环境的配置源)!