Spring基于注解配置(六)

@Profile

Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能

开发环境, 测试环境, 生产环境

数据源(A),数据源(B),数据源(C) 

@Peofile:指定组件在那个环境的情况下才能被注册到容器中;不指定,任何环境都能注册这个组件

1.创建配置类,添加数据源

@PropertySource("classpath:/dbconfig.properties")
@Configuration
@Profile("test")
public class MainConfigOfProfile {

    
    @Value("${db.user}")
    private String user;
    @Value("${db.password}")
    private String password;
    @Value("${db.driverClass}")
    private String driverClass;
    
    @Profile("test")
    @Bean
    public Yellow yellow() {
        return new Yellow();
    }
    
    @Profile("test")
    @Bean("testDataSource")
    public DataSource dataSourceTest() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setPassword(password);
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }
    
    @Profile("dev")
    @Bean("devDataSource")
    public DataSource dataSourceDev() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev");
        dataSource.setPassword(password);
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }
    
    
    @Profile("prod")
    @Bean("prodDataSource")
    public DataSource dataSourceProd() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/prod");
        dataSource.setPassword(password);
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }
}

2.创建配置文件dbconfig.properties

db.user=root
db.password=root
db.driverClass=com.mysql.jdbc.Driver

3.可以使用两种方式切换环境

  1.使用命令行动态参数,在虚拟机参数位置加载 -Dspring.profiles.active=test

  2.用代码的方式激活某种环境

下面我们使用代码的方式切换环境

@Test
    public void testIOC() {
        //1.创建ioc容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //2.设置需要激活的环境
        applicationContext.getEnvironment().setActiveProfiles("test","dev");
        //3.注册主配置类
        applicationContext.register(MainConfigOfProfile.class);
        //4.启动刷新容器
        applicationContext.refresh();
        
        String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
        for (String string : beanNamesForType) {
            System.out.println(string);
        }
        
        applicationContext.close();
    }
    
}

注意:在配置完IOC容器必须要刷新IOC容器,否则配置不会生效

在使用@Peofile需要注意:

1.加了环境标识的bean,只有这个环境被激活的时候才会注册进容器中;默认是default

2.写在配置类上,只有是指定环境的时候,整个配置类的所有配置才能生效

3.没有标注环境标识的bean在任何环境下都是加载的

posted @ 2020-06-10 17:26  丶栀爱  阅读(118)  评论(0)    收藏  举报