@Profile注解用于实现通过修改运行时参数,切换不同的开发环境
@Profile注解可以加在类上,也可以加载注入bean的方法上
下面是为了实现不同环境加载不同的数据库具体的代码
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
//@Profile("test")
@PropertySource(value = "classpath:/jdbc.properties")
@Configurable
public class MainConfigProfile implements EmbeddedValueResolverAware {
private StringValueResolver resolver;
@Value("${db.user}")
private String user;
@Value("${db.driverClass}")
private String driverCalss;
@Profile("dev")
@Bean("dataSourceDev")
public DataSource dataSourceDev(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setDriverClass(driverCalss);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
return dataSource;
}
@Profile("test")
@Bean("dataSourceTest")
public DataSource dataSourceTest(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setDriverClass(driverCalss);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ifp");
return dataSource;
}
@Profile("prod")
@Bean("dataSourceProd")
public DataSource dataSourceProd(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setDriverClass(driverCalss);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mysql");
return dataSource;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.resolver = resolver;
}
}
测试时可以加虚拟机参数-Dspring.profiles.active=XXX切换不同环境
也可以用代码设置参数,具体代码如下:
applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().setActiveProfiles("dev");
applicationContext.register(MainConfigProfile.class);
applicationContext.refresh();