问题
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