【问题标题】:Java Custom Properties File Read integer values in springJava自定义属性文件在spring中读取整数值
【发布时间】:2019-09-21 01:21:30
【问题描述】:

您好,我有自己的properties 文件,但是当我想获得order 值时它返回0,我如何在自定义弹簧属性类中读取整数值

@Component 
@PropertySource("classpath:my.properties")
@ConfigurationProperties 
public class MyProperties {

    private Integer order;

my.properties 这样的文件

enableAll=true
order=1
myvalue=ABC

【问题讨论】:

  • 你也可以发布你的属性文件
  • my.properties 在哪里?

标签: spring spring-boot properties-file


【解决方案1】:

我认为您可能缺少 getter 和 setter。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:my.properties")
@ConfigurationProperties
public class MyProperties {
    private boolean enableAll;
    private Integer order;
    private String myvalue;


    public boolean isEnableAll() {
        return enableAll;
    }

    public void setEnableAll(boolean enableAll) {
        this.enableAll = enableAll;
    }

    public Integer getOrder() {
        return order;
    }

    public void setOrder(Integer order) {
        this.order = order;
    }

    public String getMyvalue() {
        return myvalue;
    }

    public void setMyvalue(String myvalue) {
        this.myvalue = myvalue;
    }
}

通过此设置,以下测试成功运行

import com.example.demo.gq.MyProperties;
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 static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyPropertiesTests {

    @Autowired
    MyProperties myProperties;

    @Test
    public void myProps() {
        assertThat(myProperties.getOrder()).isEqualTo(1);
        assertThat(myProperties.isEnableAll()).isTrue();
        assertThat(myProperties.getMyvalue()).isEqualTo("ABC");
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多