0

It's just not working. I saw the docs at

https://docs.spring.io/spring-boot/docs/1.5.19.RELEASE/reference/htmlsingle/#boot-features-external-config

I saw the answers at

Spring boot externalize config properties/messages on Java annotations

I have

    MailTrainAPI mt = new MailTrainAPI();
    mt.sendMail(map);

...

@Component
public class MailTrainAPI {
    @Value("${mailtrain.url}")
    private String API;

    public void sendMail(MultiValueMap<String, String> map) {
        System.out.println("API = "+API);
        API = System.getProperty("mailtrain.api");
        System.out.println("API = "+API);
        API = System.getenv("mailtrain.api");
        System.out.println("API = "+API);

src/main/resources/application.properties
mailtrain.url=http://mail.galaxy.store/api/send/galaxybadge

It prints

API = null
API = null
API = null

It doesn't work because I instantiate the class myself and Spring doesn't know about it. How do I access the property in the application.properties file manually?

Spring Boot 1.5.21

Community
  • 1
  • 1
Chloe
  • 25,162
  • 40
  • 190
  • 357
  • 1
    Since `@Autowired` and `@Value` both define injections to be done by Spring, the [duplicate answer](https://stackoverflow.com/a/19896871/5221149) applies, even though it's about `@Autowired`, not `@Value`. – Andreas Aug 08 '19 at 22:07

2 Answers2

0

I was able to fix it with

public void sendMail(MultiValueMap<String, String> map) {
    try {
        setAPI();
    } catch (IOException e) {
        Logger.error(this.getClass(), "sendMail()", "Cannot send mail. Cannot load mailtrain.url property: " + e.getMessage());
        return;
    }
    if (API == null) {
        Logger.error(this.getClass(), "sendMail()", "Cannot send mail. Cannot load mailtrain.url property.");
        return;
    }
    System.out.println("API = "+API);
    ...

private void setAPI() throws IOException {
    InputStream is = this.getClass().getResourceAsStream("/application.properties");
    Properties p = new Properties();
    p.load(is);
    API = p.getProperty("mailtrain.url");
}

But I thought there would be an easier and better way with less fluff.

Chloe
  • 25,162
  • 40
  • 190
  • 357
0

MailTrainAPI is supposed to be a Spring bean, aka a component, automatically scanned because of the @Component, and then injected with the @Value("${mailtrain.url}").

However, you create a separate instance of the class yourself when you call new MailTrainAPI(). Don't do that.

Your code using the object must receive it using injection into a field, e.g.

@Autowired
private MailTrainAPI mt;
Andreas
  • 154,647
  • 11
  • 152
  • 247