Spring中使用@Profile指定不同的环境

我们在开发时,难免碰到不同环境的配置不同,比如,生产环境,测试环境,开发环境的数据库不一样。这样就需要我们指定不同环境中使用不同的URL。在Spring中,我们可以创建指定环境的Bean来解决这个问题。只有当规定的profile激活时,相应的bean才会被创建。另外没有指定profile的bean之中都会被创建,与激活哪个profile没有关系。

package com.fgcui.config;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Profile;import org.springframework.jndi.JndiObjectFactoryBean;
import javax.activation.DataSource;
@Configurationpublic class DataSourceConfig {
    
    @Bean(destroyMethod = "shutdown")
    @Profile("dev")
    public DataSource devDataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addScript("classpath::schema.sql")
            .build();    }
    
    @Bean    
    @Profile("prod")
    public DataSource prodDataSource() {
        JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();                                        
        jndiObjectFactoryBean.setJndiName("jdbc/myDs");        
        jndiObjectFactoryBean.setResourceRef(true);        
        jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);        
        return (DataSource) jndiObjectFactoryBean.getObject();    
}
}

 

那么,如何激活一个Bean呢?我们可以指定spring.profile.active属性来指定哪个环境的bean被激活。如果不指定这个属性,它会去找spring.profiles.default的值。
如果均没有指定的话,就没有激活的profile,就不会创建指定profile的bean。

有多种方式设置这个属性:

* 作为DispatcherServlet的初始化参数
* 作为Web应用的上下文参数
* 作为环境变量
* 使用@ActiveProfiles注解设置

posted @ 2017-04-27 23:04  程序员小崔  阅读(2413)  评论(0编辑  收藏  举报