Spring4 Profile

本文介绍了一个使用Spring框架实现不同环境配置切换的例子。通过定义ProfileConfig类,并利用@Profile注解来区分开发(dev)和生产(prod)环境,文章展示了如何根据当前激活的Profile选择合适的DemoBean实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Profile在不同环境下使用不同的配置提供了支持。

DemoBean.java

public class DemoBean {

    private String context;

    public DemoBean(String context) {
        super();
        this.context = context;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

}

ProfileConfig.java

@Configuration
public class ProfileConfig {

    @Bean
    @Profile("dev") // Profile为 dev时,实例化devDemoBean
    public DemoBean devDemoBean(){
        return new DemoBean(" from delelopment profile");
    }

    @Bean
    @Profile("prod") // Profile为prod时,实例化prodDemoBean
    public DemoBean prodDemoBean(){
        return new DemoBean(" from production profile");
    }

}

Main.java

public class Main {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.getEnvironment().setActiveProfiles("prod"); // 先将激活的Profile设置为prod
        ctx.register(ProfileConfig.class); // 后置注册Bean配置类,不然为报Bean未定义的错误
        ctx.refresh(); // 刷新容器

        DemoBean demoBean = ctx.getBean(DemoBean.class);

        System.out.println(demoBean.getContext());

        ctx.close();
    }

}

运行结果:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值