无法使用Java配置从属性文件访问所有属性?

时间:2019-04-15 10:17:59

标签: java spring-boot

使用Java配置(@ConfigurationProperties),我只能访问单个单词属性,如果要访问带有后缀(Ex:server.port,server.address)的属性,我需要在服务器上添加 server 配置( @ConfigurationProperties(“服务器”))。

我需要属性文件中的所有属性,我如何访问它?

//application.properties
spring.application.name=com-example
server.port=8080
minimum=200
maximum=20000
//Configuration.java

package com.example;

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

@Component
@ConfigurationProperties("server")
public class Configuration {
    private int minimum;
    private int maximum;
    private int port;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    protected Configuration() {

    }

    public Configuration(int minimum, int maximum, int port) {
        super();
        this.minimum = minimum;
        this.maximum = maximum;
        this.port = port;
    }

    public int getMinimum() {
        return minimum;
    }

    public void setMinimum(int minimum) {
        this.minimum = minimum;
    }

    public int getMaximum() {
        return maximum;
    }

    public void setMaximum(int maximum) {
        this.maximum = maximum;
    }

}

//ExampleController.java

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExampleController {

    @Autowired
    private Configuration configuration;

    @GetMapping("/properties")
    public Configuration getConfiguration() {
        return new Configuration(configuration.getMinimum(), configuration.getMaximum(),
                configuration.getPort());
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

@Component
@Configuration
public class Configuration {
    @Value("${minimum}")
    private int minimum;

    @Value("${maximum}")
    private int maximum;

    @Value("${server.port}")
    private int port;

    //Methods
}

根据Configuration,可能是名称冲突。