ritesh kumar
ritesh kumar

Reputation: 81

What is advantage of using @value annotation in Spring Boot

I am new to Spring Boot and I am doing code cleanup for my old Spring Boot application. Below code is using @Value annotation to inject filed value from properties file.

@Value("${abc.local.configs.filepath}")
private String LOCAL_ABC_CONFIGS_XML_FILEPATH;

My doubt is instead of getting value from properties file, can we not directly hardcode the value in same java class variable?

Example: private String LOCAL_ABC_CONFIGS_XML_FILEPATH="/abc/config/abc.txt"

It would be easier for me to modify the values in future as it will be in same class.

What is advantage of reading from properties file, does it make the code decoupled ?

Upvotes: 1

Views: 2623

Answers (2)

siddartha kamble
siddartha kamble

Reputation: 159

Here @value is used for reading the values from properties file (it could be a any environment like dev, qa, prod) but we are writing @value on multiple fields it is not recomonded so thats instead of @value we can use @configurableProperties(prefix="somevalue>) and read the property values suppose `

    @configurableProperties(prefix="somevalue")
        class Foo{
        string name;
        string address;
        }

application.properties:  
somevalue.name="your name"    
somevalue.address="your address"

`

Upvotes: 1

Amit Phaltankar
Amit Phaltankar

Reputation: 3424

This technique is called as externalising configurations. You are absolutely right that you can have your constants defined in the very same class files. But, sometimes, your configurations are volatile or may change with respect to the environment being deployed to.

For Example:

Scene 1: I have a variables for DB connection details which will change with the environment. Remember, you will create a build out of your application and deploy it first to Dev, then take same build to stage and finally to the production.

Having your configurations defined externally, helps you to pre-define them at environment level and have same build being deployed everywhere.

Scene 2: You have already generated a build and deployed and found something was incorrect with the constants. Having those configurations externalised gives you a liberty to just override it on environment level and change without rebuilding your application.

To understand more about externalising techniques read: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Upvotes: 1

Related Questions