转载

Spring @Value—从yml文件中引入list

在SpringBoot中要引入yml配置文件中的数组,用常用的@Value是不可取的,我们必须另寻途径。详见以下代码:

配置文件,其中mqtt是一个对象,urls是一个字符串数组,mappings是一个对象数组

mqtt:
 urls:
 - tcp://120.24.75.149:1883
 clientId: mqtt-gateway
 completionTimeout: 5000
router:
 mappings:
 - topicFilter: msg
 service: sensors
 - topicFilter: people
 service: people

配置代码:

import cn.webfuse.valuedemo.configuration.properties.Mappings;
import cn.webfuse.valuedemo.configuration.properties.MqttUrls;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DefaultConfiguration{

    @Bean
    @ConfigurationProperties(prefix = "mqtt")
    MqttUrlsmqttUrls(){
        return new MqttUrls();
    }

    @Bean
    @ConfigurationProperties(prefix = "router")
    Mappingsmappings(){
        return new Mappings();
    }


    @Value("${mqtt.clientId}")
    String clientId;

}

上述代码中用到的对象类:

public class Mapping{

    private String topicFilter;
    private String service;

    publicStringgetTopicFilter(){
        return topicFilter;
    }

    public void setTopicFilter(String topicFilter){
        this.topicFilter = topicFilter;
    }

    publicStringgetService(){
        return service;
    }

    public void setService(String service){
        this.service = service;
    }
}
public class Mappings{

    private List<Mapping> mappings = new ArrayList<>();

    publicList<Mapping>getMappings(){
        return mappings;
    }

    public void setMappings(List<Mapping> mappings){
        this.mappings = mappings;
    }

}
public class MqttUrls{

    private List<String> urls = new ArrayList<>();

    publicList<String>getUrls(){
        return this.urls;
    }

    public void setUrls(List<String> urls){
        this.urls = urls;
    }
}

使用:

@RequestMapping("/")
@RestController
public class DefaultController{

    @Autowired
    MqttUrls mqttUrls;

    @Autowired
    Mappings mappings;

    @GetMapping(value = "/urls/show")
    publicList<String>show(){

        return mqttUrls.getUrls();
    }

    @GetMapping("/mappings/show")
    publicList<Mapping>showMappings(){
        return mappings.getMappings();
    }

}
原文  http://webfuse.cn/2017/08/15/Spring @Value—从yml文件中引入list/
正文到此结束
Loading...