BAEL-2569 : EnvironmentPostProcessor in Spring Boot (#6479)

* BAEL-2569 : EnvironmentPostProcessor in Spring Boot

* BAEL-2569 add test

* BAEL-2569 update test
This commit is contained in:
letcodespeak 2019-03-13 15:58:13 +11:00 committed by maibin
parent 8ecfd8de08
commit c9ac3be4c5
9 changed files with 257 additions and 1 deletions

View File

@ -0,0 +1,59 @@
package com.baeldung.environmentpostprocessor;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.environmentpostprocessor.service.PriceCalculationService;
@SpringBootApplication
public class PriceCalculationApplication implements CommandLineRunner {
@Autowired
PriceCalculationService priceCalculationService;
private static final Logger logger = LoggerFactory.getLogger(PriceCalculationApplication.class);
public static void main(String[] args) {
SpringApplication.run(PriceCalculationApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
List<String> params = Arrays.stream(args)
.collect(Collectors.toList());
if (verifyArguments(params)) {
double singlePrice = Double.valueOf(params.get(0));
int quantity = Integer.valueOf(params.get(1));
priceCalculationService.productTotalPrice(singlePrice, quantity);
} else {
logger.error("Invalid arguments " + params.toString());
}
}
private boolean verifyArguments(List<String> args) {
boolean successful = true;
if (args.size() != 2) {
successful = false;
return successful;
}
try {
double singlePrice = Double.valueOf(args.get(0));
int quantity = Integer.valueOf(args.get(1));
} catch (NumberFormatException e) {
successful = false;
}
return successful;
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.environmentpostprocessor;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class);
public static final int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE;
private int order = DEFAULT_ORDER;
private static final String PROPERTY_PREFIX = "com.baeldung.environmentpostprocessor.";
private static final String OS_ENV_PROPERTY_CALCUATION_MODE = "calculation_mode";
private static final String OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate";
private static final String OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE = "NET";
private static final double OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0;
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
PropertySource<?> systemEnvironmentPropertySource = environment.getPropertySources()
.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
Map<String, Object> priceCalculationConfiguration = new LinkedHashMap<>();
if (isActive(systemEnvironmentPropertySource)) {
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_CALCUATION_MODE));
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE));
} else {
logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE,
OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE);
priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
}
PropertySource<?> priceCalcuationPropertySource = new MapPropertySource("priceCalcuationPS", priceCalculationConfiguration);
environment.getPropertySources()
.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, priceCalcuationPropertySource);
}
private String key(String key) {
return PROPERTY_PREFIX + key.replaceAll("\\_", ".");
}
private boolean isActive(PropertySource<?> systemEnvpropertySource) {
if (systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_CALCUATION_MODE) && systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)) {
return true;
} else
return false;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return order;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.environmentpostprocessor.autoconfig;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import com.baeldung.environmentpostprocessor.calculator.GrossPriceCalculator;
import com.baeldung.environmentpostprocessor.calculator.NetPriceCalculator;
import com.baeldung.environmentpostprocessor.calculator.PriceCalculator;
@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class PriceCalculationAutoConfig {
@Bean
@ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "NET")
@ConditionalOnMissingBean
public PriceCalculator getNetPriceCalculator() {
return new NetPriceCalculator();
}
@Bean
@ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "GROSS")
@ConditionalOnMissingBean
public PriceCalculator getGrossPriceCalculator() {
return new GrossPriceCalculator();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.environmentpostprocessor.calculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
public class GrossPriceCalculator implements PriceCalculator {
private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class);
@Value("${com.baeldung.environmentpostprocessor.gross.calculation.tax.rate}")
double taxRate;
@Override
public double calculate(double singlePrice, int quantity) {
logger.info("Gross based price calculation with input parameters [singlePrice = {},quantity= {} ], {} percent tax applied.", singlePrice, quantity, taxRate * 100);
double netPrice = singlePrice * quantity;
double result = Math.round(netPrice * (1 + taxRate));
logger.info("Calcuation result is {}", result);
return result;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.environmentpostprocessor.calculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NetPriceCalculator implements PriceCalculator {
private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class);
@Override
public double calculate(double singlePrice, int quantity) {
logger.info("Net based price calculation with input parameters [singlePrice = {},quantity= {} ], NO tax applied.", singlePrice, quantity);
double result = Math.round(singlePrice * quantity);
logger.info("Calcuation result is {}", result);
return result;
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.environmentpostprocessor.calculator;
public interface PriceCalculator {
public double calculate(double singlePrice, int quantity);
}

View File

@ -0,0 +1,17 @@
package com.baeldung.environmentpostprocessor.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baeldung.environmentpostprocessor.calculator.PriceCalculator;
@Service
public class PriceCalculationService {
@Autowired
PriceCalculator priceCalculator;
public double productTotalPrice(double singlePrice, int quantity) {
return priceCalculator.calculate(singlePrice, quantity);
}
}

View File

@ -1 +1,7 @@
org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig
org.springframework.boot.env.EnvironmentPostProcessor=\
com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor

View File

@ -0,0 +1,26 @@
package com.baeldung.environmentpostprocessor;
import static org.junit.Assert.assertEquals;
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.junit4.SpringRunner;
import com.baeldung.environmentpostprocessor.service.PriceCalculationService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PriceCalculationApplication.class)
public class PriceCalculationEnvironmentPostProcessorLiveTest {
@Autowired
PriceCalculationService pcService;
@Test
public void whenSetNetEnvironmentVariablebyDefault_thenNoTaxApplied() {
double total = pcService.productTotalPrice(100, 4);
assertEquals(400.0, total, 0);
}
}