spring启动时通过指定profile加载不同的bean

有时候我们有多个环境,开发环境、测试环境、生产环境,每个环境都有不同的配置信息

如何用一套代码,在不同环境上都能运行,spring的profile就是用来解决这个问题

比如想着测试环境加载一个配置类,那么这个类可以加上这个注解

一、命令行和@Profile注解用法

@Component
@Profile(value="test")
public class ZKWorkerClient {}

在运行jar包时只需要使用如下命令,就可以加载这个对象

java -jar *.jar -Dspring.profile.active=test

 @Profile修饰类

@Configuration
@Profile("prod")
public class JndiDataConfig {

    @Bean(destroyMethod="")
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
    }
}

@Profile修饰方法

@Configuration
public class AppConfig {

    @Bean("dataSource")
    @Profile("dev")
    public DataSource standaloneDataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:com/bank/config/sql/schema.sql")
            .addScript("classpath:com/bank/config/sql/test-data.sql")
            .build();
    }

    @Bean("dataSource")
    @Profile("prod")
    public DataSource jndiDataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
    }
}

参考:https://blog.csdn.net/loongkingwhat/article/details/105745303

二、配置多种开发环境

有时候开发是一种环境,生产又是一种环境,我们需要从配置文件灵活读取各种参数

 这时候就需要用配置文件来解决

在application.properties指定

spring.profiles.active=prod

然后再另外两个配置文件中配置不同的参数,比如application-dev.properties

profile.url.call=http://cloudcall
profile.url.workOrder=http://cloud-workorder

在写一个config类,从properties文件里读取

/**
 * @Author : wangbin
 * @Date : 2021/5/8 9:43
 */
@ConfigurationProperties("profile.url")
@Component
public class BaseUrlConfig implements Serializable {
    private static final long serialVersionUID = 2092752356451204202L;

    private String call;

    private String workOrder;

    public void setCall(String call) {
        this.call = call;
    }

    public void setWorkOrder(String workOrder) {
        this.workOrder = workOrder;
    }

    public String getCall() {
        return call;
    }

    public String getWorkOrder() {
        return workOrder;
    }
}

这时候应用读到的就是prod配置文件里的内容了

原文地址:https://www.cnblogs.com/wangbin2188/p/14713661.html