В этой статье мы покажем вам, как использовать @Profile
в Spring Boot, а также как его протестировать.
Протестировано с:
- Пружинный ботинок 2.1.2. ВЫПУСК
- Мавен 3
1. Структура проекта
Стандартная структура проекта Maven.
2. Зависимость от проекта
4.0.0 spring-boot-profile jar Spring Boot Profiles Example Spring Boot Profiles Example https://www.mkyong.com 1.0 org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.apache.maven.plugins maven-surefire-plugin 2.22.0
3. Пружинный ботинок
В Spring Boot профиль по умолчанию – ” по умолчанию
“. Ознакомьтесь со следующими метеорологическими службами.
3.1 Интерфейс.
package com.mkyong.service; public interface WeatherService { String forecast(); }
3.2 Профиль: солнечный и по умолчанию.
package com.mkyong.service; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; @Service @Profile({"sunny", "default"}) public class SunnyDayService implements WeatherService { @Override public String forecast() { return "Today is sunny day!"; } }
3.3 Профиль: идет дождь.
package com.mkyong.service; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; @Service @Profile("raining") public class RainingDayService implements WeatherService { @Override public String forecast() { return "Today is raining day!"; } }
3.4 Запустите приложение Spring Boot.
package com.mkyong; import com.mkyong.service.WeatherService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private WeatherService weatherService; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) { System.out.println(weatherService.forecast()); } }
3.5 Файл свойств.
# default profile is 'default' #spring.profiles.active=sunny logging.level.=error spring.main.banner-mode=off
4. Модульный тест
Некоторые примеры модульных тестов.
4.1 Модульное тестирование класса обслуживания. Установите активный профиль через @activeprofiles
package com.mkyong; import com.mkyong.service.WeatherService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("raining") public class TestWeatherService { @Autowired WeatherService weatherService; @Test public void testRainingProfile() { String output = weatherService.forecast(); assertThat(output).contains("Today is raining day!"); } }
4.2 Модульное тестирование приложения Spring Boot. Вы можете установить активный профиль через свойство spring.profiles.active
package com.mkyong; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.springframework.boot.test.rule.OutputCapture; import static org.assertj.core.api.Assertions.assertThat; public class TestApplication { @Rule public OutputCapture outputCapture = new OutputCapture(); @Test public void testDefaultProfile() { Application.main(new String[0]); String output = this.outputCapture.toString(); assertThat(output).contains("Today is sunny day!"); } @Test public void testRainingProfile() { System.setProperty("spring.profiles.active", "raining"); Application.main(new String[0]); String output = this.outputCapture.toString(); assertThat(output).contains("Today is raining day!"); } @Test public void testRainingProfile_withDoption() { Application.main(new String[]{"--spring.profiles.active=raining"}); String output = this.outputCapture.toString(); assertThat(output).contains("Today is raining day!"); } @After public void after() { System.clearProperty("spring.profiles.active"); } }
P.S Заслуга этого весеннего ботинка Примеры Тестов Приложений Профиля
5. ДЕМОНСТРАЦИЯ
Упакуйте и запустите его.
$ mvn package #default profile, sunny day! $ java -jar target/spring-boot-profile-1.0.jar Today is sunny day! # set a profile $ java -jar -Dspring.profiles.active=raining target/spring-boot-profile-1.0.jar Today is raining day!
Скачать Исходный Код
Рекомендации
- Пример профилей пружин
- Пружинная загрузка – Свойства и конфигурация
- Пружинный ботинок – Профили
- Документы CommandLineRunner
Оригинал: “https://mkyong.com/spring-boot/spring-boot-profiles-example/”