springboot @Value 類中讀取配置文件 .properties null 原因和解決方案


問題:在一個工具類中,通過@Value來映射配置文件的值,得到的總是null

原因:不能用new工具類的方式,應該是用容器注冊(@Autowried)的方式使用此工具類,就能得到配置文件里的值

 

上代碼:

工具類:

package com.***.***.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import system.Decimal;

import java.math.BigDecimal;

@Component
public class RoundCalculationUtil {

    @Value("${***.round.calculation}") private String calculationWay; public BigDecimal reCalculateAmount(BigDecimal amount){
        if(calculationWay.equals("currencyround")){
            return currencyRound(amount);
        }else {
            return round(amount);
        }
    }

    public BigDecimal 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"));
        }

        return result;
    }

    public BigDecimal 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"));
        }
        return result;
    }

}

 

調用處:

@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 new ResponseData(NotificationMsg.SUCCESS, df.format(result));
        } catch (Exception e) {
            logger.error(e);
            return new ResponseData(NotificationMsg.FAILED, e);
        }

    }

 

打賞

免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2021 CODEPRJ.COM