So you'd like to access one or more of the values in your application.properties file from your Spring Boot code?

No problem. I'll show you how to do it here.

And this trick also works with application.yml, if that's how you roll.

I'm not a huge fan of the awkward spacing and indentation requirements of YAML, so I tend to stick to old-fashioned properties files myself.

In either case, here's how you do it.

You Have Value

Here's a little application.properties file I'm using right now:

server.port=36120

mongo.zip.collection=zips

mongo.db=mongodb://joe:password@1.2.3.4:27017/ecosystem
mongo.db.name=ecosystem

Now let's say I want to access that mongo.db property. 

(In fact, I do.)

Here's how I'd go about it in one of my classes:

@Value("${mongo.db}")
private String mongoConnection;

That's it. Just use the @Value annotation above the Java property you want set to the application.properties value.

In the example above, the Spring framework will set the value of mongoConnection to "mongodb://joe:password@1.2.3.4:27017/ecosystem".

That's because that happens to be the value of the mongo.db property in application.properties.

Now pay attention to the awkward notation next to the @Value annotation. That's what you're going to have to do as well.

Yep. It's braces followed by a dollar sign in quotation marks within parentheses.

Don't shoot the messenger.

But that will give you exactly what you're looking for.

Another Way

Here's another thing you can do.

First, autowire the Environment.

@Autowired
private Environment env;

Then, grab the property you're looking for like so:

String mongoConnection = env.getProperty("mongo.db");

Using that method, you can avoid the awkward notation that you need to use with @Value.

But, honestly, I'm still a fan of @Value myself.

Wrapping It Up

There you have it. A couple of easy ways to get the values from application.properties into your Spring Boot code.

Now it's your turn. Take what you've learned here and use it in your own development efforts.

Have fun!

Photo by Karolina Grabowska from Pexels