Spring常用配置-Profile

一、Profile是什麼?

在企業開發中,項目開發環境和產品環境的配置是不同的(如數據庫的配置)。
Profile爲不同環境下使用不同的配置提供了支持

二、如何使用profile

  1. 通過設定Environment的ActiceProfile來設定當前context(容器)需要使用的配置環境
    開發中通常使用@Profile註解,達到不同情況實例化不同Bean的目的

三、ProfileDemo

demobean

package com.cactus.demo.profile;

/**
 * Created by liruigao
 * Date: 2019-10-15 14:31
 * Description:
 */


public class DemoBean {
    private String content;

    public DemoBean() {
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

配置類

package com.cactus.demo.profile;

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

/**
 * Created by liruigao
 * Date: 2019-10-15 14:32
 * Description:
 */

@Configuration
public class ProfileConfig {
    @Bean
    @Profile("dev")
    public DemoBean getDemoBeanDev() {
        return new DemoBean("this is dev env");
    }

    @Bean
    @Profile("prod")
    public DemoBean getDemoBeanProd() {
        return new DemoBean("this is prod env");
    }
}

Main

package com.cactus.demo.profile;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by liruigao
 * Date: 2019-10-15 14:34
 * Description:
 */


public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.getEnvironment().setActiveProfiles("prod");
        // 需要後置註冊配置類,否則會報error
        context.register(ProfileConfig.class);
        context.refresh();
        DemoBean bean = context.getBean(DemoBean.class);
        System.out.println(bean.getContent());
        context.close();
    }
}

result
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章