问题:在一个工具类中,通过@Value来映射配置文件的值,得到的总是null
原因:不能用new工具类的方式,应该是用容器注册(@Autowried)的方式使用此工具类,就能得到配置文件里的值
上代码:
工具类:
package com.***.***.utils; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.stereotype.Component; importsystem.Decimal; importjava.math.BigDecimal; @Component public classRoundCalculationUtil { @Value("${***.round.calculation}") privateString calculationWay; publicBigDecimal reCalculateAmount(BigDecimal amount){ if(calculationWay.equals("currencyround")){ returncurrencyRound(amount); }else{ returnround(amount); } } publicBigDecimal round(BigDecimal amount) { BigDecimal result = amount.setScale(0, BigDecimal.ROUND_DOWN); BigDecimal lastRound2 = amount.setScale(2, BigDecimal.ROUND_DOWN).subtract(result); if (lastRound2.compareTo(new BigDecimal("0.50")) >= 0) { result = result.add(new BigDecimal("1")); } returnresult; } publicBigDecimal currencyRound(BigDecimal amount){ BigDecimal result = amount.setScale(2,BigDecimal.ROUND_DOWN); BigDecimal firstRound4=amount.setScale(4,BigDecimal.ROUND_DOWN); BigDecimal lastRound2=firstRound4.subtract(firstRound4.setScale(2,BigDecimal.ROUND_DOWN)); if(lastRound2.compareTo(new BigDecimal("0.0005"))>=0){ result=result.add(new BigDecimal("0.01")); } returnresult; } }
调用处:
@Autowired RoundCalculationUtil roundCalculationUtil; @RequestMapping(value = "/roundtest", method =RequestMethod.GET) public ResponseData<String> roundTest(@RequestParam(value = "amount", required = true, defaultValue = "100.1111") BigDecimal amount, @RequestParam(value = "roundcalculation", required = false, defaultValue = "currencyround") String roundcalculation) { try{ BigDecimal result=roundCalculationUtil.reCalculateAmount(amount); //BigDecimal result=new RoundCalculationUtil ().reCalculateAmount(amount);//will get null from .properties file DecimalFormat df = new DecimalFormat("0.00"); return newResponseData(NotificationMsg.SUCCESS, df.format(result)); } catch(Exception e) { logger.error(e); return newResponseData(NotificationMsg.FAILED, e); } }