Video in progress
How do you read a configuration value with the @Value annotation?
@Value("${key}") takes the value from the Environment and puts it into a field or parameter; with ${key:default} you can also give a default value.
📖 Answer
@Service
public class MailService {
private final String from;
private final int retries;
public MailService(@Value("${mail.from}") String from,
@Value("${mail.retries:3}") int retries) {
this.from = from;
this.retries = retries;
}
}
${mail.from} comes from application.yml, an env variable or another source. :3 is the value used when the key isn't found. If there's no default and no key either, the application fails at startup. Spring converts the type itself: int, boolean, Duration ("30s") and so on.
It works from the env too: MAIL_FROM → mail.from (relaxed binding).
When you have a lot of settings with the same prefix, don't pull them one by one with @Value — collecting them into a @ConfigurationProperties class is more convenient and easier to validate.
Sign up to mark studied questions and save your progress.