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注解设置

转载于:https://www.cnblogs.com/fgcui/p/6777802.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值