Multiple string values from application.yaml file

Anil R
Nov 19, 2024

--

@ConfigurationProperties is a Spring annotation used to bind external configuration properties (like those from .properties or .yaml files) to Java objects in a type-safe manner. This feature is commonly used in Spring Boot applications to manage application-specific settings in a structured way.

Defining a Configuration Class

Use @ConfigurationProperties to specify the prefix of the properties to bind.

application.yml

myapp:
events:
- approved
- rejected
- inprocess
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConfigurationProperties(prefix = "myapp")
public class EventsConfig {

private List<String> events; // We can also use String[] events;

public List<String> getEvents() {
return events;
}

public void setEvents(List<String> events) {
this.events = events;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyEventsService {

private final EventsConfig eventsConfig;

@Autowired
public MyService(EventsConfig eventsConfig) {
this.eventsConfig = eventsConfig;
}

public boolean hasEvents(String input) {
return eventsConfig.getEvents().contains(input);
}
}

--

--

Anil R
Anil R

Written by Anil R

Full Stack Developer with 15 years experience.

No responses yet