Jonathon Ashworth
Jonathon Ashworth

Reputation: 1114

How do @value annotations work in Spring?

I've never worked with Spring before, and I've run into a configuration object that looks somewhat like this

public class Config {

@Value("${app.module.config1}")
private String config1;

@Value("${app.module.config2}")
private String config2

...

public String getConfig1() {
    return config1;
}

...

Can anyone explain what is happening here? I'm assuming this is some type of code injection, but I can't find where these values are coming from!

Upvotes: 3

Views: 7889

Answers (2)

Vikdor
Vikdor

Reputation: 24134

@Value("${app.module.config1}")

This is part of the spring expression language where the spring framework would look for app.module.config1 JVM property from System.getProperties() and injects the value of that property into config1 attribute in that class. Please see this reference for more details in Spring 3.0.x and this reference for the current docs.

Upvotes: 3

dinox0r
dinox0r

Reputation: 16059

They allow you to direct inject a Value from a properties file (system or declared property) in the variable. Using the util:properties tag you can add something like this in your applicationContext.xml

 <util:properties id="message" location="classpath:com/your/program/resources/message.properties" />

Pointing for a properties file named "message.properties" with some content:

 application.hello.message = Hello World!

And then, in your java source file, inject a direct value from this properties file using the @Value annotation:

 @Value("#{message['application.hello.message']}")
 private String helloWorldMessage;

Upvotes: 4

Related Questions