4

I'm creating a component for mail service configuration >>

@Component
@PropertySource("classpath:mail.properties")
public class Mail {

  @Value("${email.config.host}")
  private String host;

  @Value("${email.config.port}")
  private Integer port;

  @Value("${email.config.username}")
  private String username;
}

And my mail.properties file looks like >>

email.config.host=smtp.gmail.com
email.config.port=587
email.config.username=idontknowmyname@gmail.com
email.config.password=password

I tried to get my port value, but I got problem >

java.lang.NumberFormatException: For input string: "${email.config.port}"

Yes, I know this should be an Integer value but my @Value annotation converted** to String. So I tried this:

@Value("#{ T(java.lang.Integer).parseInt('${email.config.port}')}")

... got the same.

Host, username, password, etc. Loaded fine! How can I get my port value? Why PropertySource did not convert this parameter automatically?

davidwillianx
  • 391
  • 2
  • 5
  • 13

2 Answers2

3

Spring is able to convert such values from string to integer, if the string represent an integer.

But if spring is not able to find the property in the properties, then it set its value to its (missing) key. And this result in a string that is no parseable number.

Therefore it is likely that Spring is not able to find your email.config.port property. - You can prove this, buy having a String field annotated with @Value("${email.config.port}").

Ralph
  • 118,862
  • 56
  • 287
  • 383
  • Sr. as set in my first answer. I posted the wrong @Value parameter. I'll change this thing right now. That fact is, right parameter (key) wont make this works. – davidwillianx Dec 01 '16 at 00:46
  • @davidwillianx: Have you tryed the suggested String based test? – Ralph Dec 02 '16 at 13:40
  • You mean set port variable as String? How can I set this value to my framework configuration object, cause it's allow int only. – davidwillianx Dec 05 '16 at 13:19
  • @davidwillianx: no I mean try just: `@Value("${email.config.port}") String portAsStringTest;` .... `@PostConstruct post(){System.out.println("portAsStringTest: " + portAsStringTest)}` – Ralph Dec 05 '16 at 13:40
  • String type works perfect! Are you trying to instruct me to convert this String value into Int / Integer value insider of @PostContruct method? got the same error >> java.lang.NumberFormatException: For input string: "${email.config.port}" – davidwillianx Dec 05 '16 at 13:58
-2

Add @Configuration annotation to work with externalized values.

viruskimera
  • 193
  • 16