繁体   English   中英

Springboot 无法从属性文件中读取值

[英]Springboot can't read values from properties file

我有以下问题:我想从.properties文件中读取一些值(产品的价格)。

但是我正在尝试,它总是以0.00作为值。

这是我的服务 bean,我想在其中创建一个产品列表:

@Service
@ConfigurationProperties(prefix = "product-service")
public class ProductService {

    private double first;
    private double second;
    private double third;

    public double getFirst() {
        return first;
    }

    public void setFirst(double first) {
        this.first = first;
    }

    public double getSecond() {
        return second;
    }

    public void setSecond(double second) {
        this.second = second;
    }

    public double getThird() {
        return third;
    }

    public void setThird(double third) {
        this.third = third;
    }

    private List<ProductDTO> productList = Arrays.asList(
            new ProductDTO(1, "Tomb Raider", first),
            new ProductDTO(2, "10000 rp to lol", second),
            new ProductDTO(3, "2k valorant points", third)
    );

    public List<ProductDTO> findAllProducts() {
        return productList;
    }
}

这是属性文件:

product-service.first = 225.00
product-service.second = 320.50
product-service.third = 150.99

考虑到您使用prefix = "product-service"

您应该如下声明您的 class 字段。

    private double first;
    private double second;
    private double third;

您还应该更新 getter 和 setter。

您的代码中还有另一个错误

private List<ProductDTO> productList = Arrays.asList(
            new ProductDTO(1,"Tomb Raider",first),
            new ProductDTO(2,"10000 rp to lol",second),
            new ProductDTO(3,"2k valorant points",third)
    );

当您的 class 被初始化时,该字段被初始化。 但是 Spring 使用代理初始化您的 bean。 因此,当productList被初始化时,您的 productList 的firstsecondthird将具有0值。

如果你希望这个工作你应该更换

public List<ProductDTO> findAllProducts() {
        return productList;
    }

public List<ProductDTO> findAllProducts() {
        return Arrays.asList(
                new ProductDTO(1,"Tomb Raider",first),
                new ProductDTO(2,"10000 rp to lol",second),
                new ProductDTO(3,"2k valorant points",third)
        );
    }

不要将您的配置属性与服务层混合。

你有几种方法:

  • 创建一个单独的配置 class:
@ConfigurationProperties("product-service")
public class ProductProperties {
    private Double first;
    private Double second;
    private Double third;
    // getters & setters
}

并直接在您的服务中使用它 class:

class ProductService {
    private ProductProperties properties;

    // use at code: properties.getFirst()
}

根据您的 Spring 引导版本,您可能需要在标有@Configuration的任何 class 下使用@EnableConfigurationProperties({ProductProperties.class})

  • 使用@Value
class ProductService {
    @Value("${product-service.first}")
    private double first;
    //...
}

您应该设置为您的主要 class:

有用的链接:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM