07-SpringBoot——Spring常用配置-Profiles

Spring常用配置-Profiles


【博文目录>>>】


【项目源码>>>】


【Profiles】


Profile 为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如,数据库的配置)。

(1) 通过设定Environment 的ActiveProfiles 来设定当前context 需要使用的配置环境。在开发中使用@Profile 注解类或者方法,达到在不同情况下选择实例化不同的Bean。
(2) 通过设定jvm 的spring.profiles.active 参数来设置配置环境。
(3) Web 项目设置在Servlet 的context parameter 中。

Servlet 2.5 及以下:
这里写图片描述

Servlet 3.0 及以上:
这里写图片描述

【代码实现】

package com.example.spring.framework.profile;

/**
 * Author: 王俊超
 * Date: 2017-07-11 07:26
 * All Rights Reserved !!!
 */
public class DemoBean {
    private String content;

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
package com.example.spring.framework.profile;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;

/**
 * ① Profile 为dev 时实例化devDemoBean。
 * ② Profile 为prod 时实例化prodDemoBean。
 * Author: 王俊超
 * Date: 2017-07-11 07:26
 * All Rights Reserved !!!
 */
public class ProfileConfig {

    @Bean
    @Profile("dev") //1
    public DemoBean devDemoBean() {
        return new DemoBean("from development profile");
    }

    @Bean
    @Profile("prod") //2
    public DemoBean prodDemoBean() {
        return new DemoBean("from production profile");
    }
}
package com.example.spring.framework.profile;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Author: 王俊超
 * Date: 2017-07-11 07:26
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        activeProfiles("dev");
        activeProfiles("prod");

    }

    /**
     * ①先将活动的Profile 设置为参数传的值
     * ②后直注册Bean 配置类,不然会报Bean 未定义的错误。
     * ③刷新容器。
     *
     * @param profiles
     */
    private static void activeProfiles(String... profiles) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext();

        context.getEnvironment().setActiveProfiles(profiles); //1
        context.register(ProfileConfig.class);//2
        context.refresh(); //3

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

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

        context.close();
    }
}

【运行结果】

这里写图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值