Aditya T
Aditya T

Reputation: 1733

How do I read application properties in Micronaut?

I integrated AWS SES API to my Micronaut Groovy application using guide send mail in micronaut and I am able send mails if I directly assign values to properties.

I want to make it config driven hence have been trying to find ways to achieve that.

I tried @Value annotation as mentioned in guide but was not able to make it work.

@Value("aws.secretkeyid")
String keyId

Further digging into documentation revealed that Micronaut has its own annotation for injecting properties in variables.

@Property(name="aws.secretkeyid")
String keyId

But nothing seems to work, my variables are still null.

What could be possibly wrong here ?

For reference, following is in my application.yml file

aws:
  keyid: "2weadasdwda"
  secretkeyid: "abcdesdasdsddddd"
  region: "us-east-1"

Upvotes: 12

Views: 27177

Answers (3)

MechCoder
MechCoder

Reputation: 29

One more note, it appears both @Property(name = "your.application.property") and @Value("${aws.secretkeyid}") will not make the variable available in the constructor.

However, it can be passed as a parameter to the constructor like so:

public Constructor (@Property(name = "your.application.property") String property) { ... }

Upvotes: 1

You are using it incorrectly, you are injecting the literal value aws.secretkeyid, not the value of a variable.

The correct syntax is (Groovy):

@Value('${aws.secretkeyid}')
String keyId

Notice that you must use single quotes to avoid Groovy to attempt interpolation

Java:

@Value("${aws.secretkeyid}")
String keyId;

Kotlin:

@Value("\${aws.secretkeyid}")
keyId: String

Notice that you must use a backslash to escape the dollar sign to avoid Kotlin string templates

Upvotes: 23

Aditya T
Aditya T

Reputation: 1733

If anyone else stumbles upon this problem, you also have alternative to use @Property annotation in Micronaut ( starting from version 1.0.1 )

Syntax is as follows

@Property(name = "your.application.property")
String propertyName

PS : This is what was mentioned in Micronaut Documentation but was not working in my case as I was on Micronaut Version 1.0.0

Upvotes: 10

Related Questions