Total Pageviews

2019/04/08

[Spring Boot] A simple example for Spring Boot Profile

Scenario


How-To
1. Create a WeatherService
package com.example.service;

public interface WeatherService {

    String getWeatherForecast();

}


2. Create a SunnyDayService and assign sunny & default
package com.example.service;

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

@Service
@Profile({"sunny", "default"})
public class SunnyDayService implements WeatherService {

    @Override
    public String getWeatherForecast() {
        return "Today is sunny day";
    }

}


3. Create a RainingDayService and assign raining profile
package com.example.service;

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

@Service
@Profile({"raining"})
public class RainyDayService implements WeatherService {

    @Override
    public String getWeatherForecast() {
        return "Today is raining day";
    }

}


4. Assign active profile in application.yml
spring:
  profiles:
    active: raining


5. Test code
package com.example.test;

import com.example.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.example")
@Slf4j
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
 
    @Bean
    CommandLineRunner testWeatherService(WeatherService weatherService) {
        return args -> {
            String output = weatherService.getWeatherForecast();
            log.debug("weather forecast = {}", output);
        };
    }

}



Console
2018-12-20 09:53:30.255 DEBUG 6920 --- [           main] com.example.test.TestApplication         : weather forecast = Today is raining day


No comments: