Spring注解(十一) @Profile

127 阅读1分钟

作用: 切换环境比如数据源等

测试

向ioc容器编写三个bean name不同的datasource, 标注上@Profile, 只会向容器注入一个bean 默认为"default"

@Configuration
public class ProfileTest {
    @Profile("default")
    @Bean("testDataSource")
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/vuedb?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }
    @Profile("test")
    @Bean("testDataSource1")
    public DataSource dataSource2() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }
    @Profile("dev")
    @Bean("testDataSource2")
    public DataSource dataSource3() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/Mysql50?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }
}

测试

@Test
public void test() {
    AnnotationConfigApplicationContext ioc = getIoc(ProfileTest.class);
    printBeans(ioc);
}
// 结果
profileTest
testDataSource

切换profile方法

  1. 虚拟机参数
-Dstring.profiles.active=test
  1. 创建无参构造的ioc容器