Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 998
Jonathon Ashworth Avatar asked Dec 11 '25 14:12

Jonathon Ashworth


2 Answers

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;
like image 133
higuaro Avatar answered Dec 13 '25 04:12

higuaro


@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.

like image 24
Vikdor Avatar answered Dec 13 '25 03:12

Vikdor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!