Spring @Value with arraylist split and obtain the first value

北城以北 提交于 2020-06-17 15:48:31

问题


Spring @Value with arraylist split and get the first value of arrayList

I had my.list=a,b,c
I am struggling to get the first value i.e., a

I tried,

@Value("#{'${my.list}'.split(',')})
List<String> values;
String myVal = values.get(0);

Is there any better method than this procedure?


回答1:


U have a syntax error in this line

@Value("#{'${my.list}'.split(',')})

That should be corrected as below

@Value("#{'${my.list}'.split(',')}")
List<String> values;

I would suggest you below solution as a better method

A domain class

@Component
public class Data {


    @Value("#{'${my.list}'.split(',')}")
    List<String> values;



    public List<String> getValues() {
        return values;
    }

    public void setValues(List<String> values) {
        this.values = values;
    }

}

This how you can use the domain class

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


    @Autowired
    Data data;

    @GetMapping
    public String hello(ModelMap model) {

        return data.getValues().get(0);

    }

}

application.properties file

my.list=a,b,c

You can take that value directly as below

@Value("#{'${my.list}'.split(',')[0]}")
String values;



回答2:


@Autowired
Environment env;

//To get the List<String>
List<String> values = Arrays.asList(env.getProperty("my.list").split(",");

//Then, you can get value into an Optional to prevent NullPointerException
Optional<String> myValue = values.stream().findFirst();


来源:https://stackoverflow.com/questions/56454902/spring-value-with-arraylist-split-and-obtain-the-first-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!