1. 程式人生 > 實用技巧 >SpringBoot使用@Profile指定執行環境

SpringBoot使用@Profile指定執行環境

SpringBoot使用@Profile指定執行環境

實際開發中我們需要為不同的環境做不同的配置,如下圖:

1.application.yml

application.yml是預設使用的配置檔案,在其中通過spring.profiles.active設定使用哪一個配置檔案,下面程式碼表示使用application.prod.yml配置,如果application.prod.yml和application.yml配置了相同的配置,比如都配置了執行埠,那application.prod.yml會覆蓋application.yml的配置

#需要使用的配置檔案
spring:
  profiles:
    active: prod
    #spring.profiles.include屬性用來設定無條件的啟用哪些profile
    #include: prod 

2. VM options、Program arguments、Active Profile

VM options設定啟動引數 -Dspring.profiles.active=prod
Program arguments設定 --spring.profiles.active=prod
Active Profile 設定 prod
這三個引數不要一起設定,會引起衝突,選一種即可,如下圖

3. 命令列

將專案打成jar包,在jar包的目錄下開啟命令列,使用如下命令啟動:

java -jar spring-boot-profile.jar --spring.profiles.active=prod

上面是profile在配置檔案上的應用,同時profile還可以用在類上,spring提供了@Peofile註解可以實現不同環境下配置引數的切換,任何@Component或@Configuration註解的類都可以使用@Profile註解。

我們可以在配置類上使用@Profile註解,如下,該配置只會在prod環境下生效

@Configuration
@Profile("prod")
public class ProductionConfiguration {
    // ...
}

如果在實現類上加上@Profile註解,則可以實現注入介面時根據當時的配置環境動態注入對應的實現類。下面是一個例子:
有一個HelloService介面

package com.along.service;

public interface HelloService {
    String hello();
}

對HelloService介面做了兩個實現,分別對應於生產環境和開發環境,如下

package com.along.service;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

/**
 * 生產環境實現類
 */
@Service
@Profile("dev")
public class DevServiceImpl implements HelloService {

    @Override
    public String hello() {
        return "use dev";
    }
}
package com.along.service;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

/**
 * 開發環境實現類
 */
@Service
@Profile("prod")
public class ProdServiceImpl implements HelloService {

    @Override
    public String hello() {
        return "use prod";
    }
}

然後寫一個介面呼叫HelloService

package com.along.controller;

import com.along.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @RequestMapping("hello")
    public String sayHello(){
        return helloService.hello();
    }
}

當前啟用的配置環境是prod,application.yml配置如下

spring:
  profiles:
    active: prod

啟動專案,瀏覽器訪問http://localhost:8082/hello,介面返回use prod,再改變application.yml配置,啟用dev,重啟專案,再次訪問介面返回use dev,說明@Profile註解起到了作用,實現了根據當時的配置環境動態的選擇相應的實現類。