parhau
parhau

Reputation: 207

Spring @Value with arraylist split and obtain the first value

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?

Upvotes: 1

Views: 7107

Answers (2)

Lahiru Wijesekara
Lahiru Wijesekara

Reputation: 662

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;

Upvotes: 2

Pablo Carmona
Pablo Carmona

Reputation: 91

@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();

Upvotes: 0

Related Questions